Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

peewee create and use id field for deferred foreign key with primary_key=true #2427

Closed
penja opened this issue Jun 7, 2021 · 0 comments
Closed

Comments

@penja
Copy link

penja commented Jun 7, 2021

Hello. We have the deferred foreign key that used like primary key in new table. In this case peewee ignore primary_key=True param in column declaration and try to use id like identifier in all sql queries.
Please see invalid behavior in following code snippet.

import peewee
from peewee import *
import logging
import sys

log = logging.getLogger()
log.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
log.addHandler(handler)

print(peewee.__version__)

db = SqliteDatabase(":memory:")


class Base(Model):
    class Meta:
        database = db


class B(Base):
    a = DeferredForeignKey("A", primary_key=True)
    x = CharField(null=True)


class A(Base):
    id = AutoField()

db.create_tables([B, A])

Output

root@87a4315fc6f4:/vagrant# python dummy_sqlite.py 
3.14.4
('CREATE TABLE IF NOT EXISTS "a" ("id" INTEGER NOT NULL PRIMARY KEY)', [])
('CREATE TABLE IF NOT EXISTS "b" ("id" INTEGER NOT NULL PRIMARY KEY, "a_id" INTEGER NOT NULL PRIMARY KEY, "x" VARCHAR(255))', [])
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/peewee.py", line 3144, in execute_sql
    cursor.execute(sql, params or ())
sqlite3.OperationalError: table "b" has more than one primary key

During handling of the above exception, another exception occurred:

Thanks in advance for your response and probably for the fix.

P.S There is workaround by in my opinion this is not obvious!

class B(Base):
    class Meta:
        primary_key = False

    a = DeferredForeignKey("A", primary_key=True)
    x = CharField(null=True)
#or
class B(Base):
    class Meta:
        primary_key = peewee.CompositeKey("a")
    a = DeferredForeignKey("A")
    x = CharField(null=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant