Code

Opened 2 years ago

Last modified 4 weeks ago

#18081 new Bug

Proxy model foreign keys not created properly by syncdb

Reported by: akaariai Owned by: nobody
Component: Database layer (models, ORM) Version: 1.4
Severity: Normal Keywords:
Cc: charette.s@… Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: yes
Easy pickings: no UI/UX: no

Description

Add this test to modeltests/proxy_models/tests.py:

class TransactionalProxyModelTests(TransactionTestCase):
    def test_proxy_fk(self):
        """
        Test that the DB contains proper foreign keys for proxy model references.
        """
        @transaction.commit_on_success
        def create_failing_pk():
            t = TrackerUser.objects.create(status='bar')
            Improvement.objects.create(summary='foof', version='foof',
                                       reporter_id=1, associated_bug_id=1,
                                       assignee=t)
        self.assertRaises(IntegrityError, create_failing_pk)

On MySQL this does not fail when using InnoDB. It should fail, as both reporter and associated bug with ID=1 are missing.

The reason for this is that in django/db/backends/creation.py, sql_for_pending_references() is a check:
if not model._meta.managed or model._meta.proxy: skip creation 
Now, that is incorrect: the model in question is the model we are _referring_, not the model from where the PK is from. So, under MySQL foreign keys to proxy models do not get enforced in the DB.

In addition the same bug is there for other databases, too. However, this one does not show under PostgreSQL as the foreign key is created inline. However, were the order of the models different in models.py also PostgreSQL would fail to create the foreign key.

The fix is luckily very simple: just remove the "or proxy" part. The managed part is correct: the referenced model can be a view for example, in which case referencing it would be a failure.

Attachments (0)

Change History (3)

comment:1 Changed 2 years ago by aaugustin

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Accepted

comment:2 Changed 2 years ago by charettes

  • Cc charette.s@… added

comment:3 Changed 4 weeks ago by timo

  • Patch needs improvement set

Two years later, I guess the branch probably doesn't merge cleanly.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as new
The owner will be changed from nobody to anonymous. Next status will be 'assigned'
as The resolution will be set. Next status will be 'closed'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.