Opened 22 months ago

Last modified 22 months ago

#34311 closed Cleanup/optimization

Update serialization examples from unique_together to UniqueConstraint — at Version 6

Reported by: Willem Van Onsem Owned by: Willem Van Onsem
Component: Documentation Version: 4.1
Severity: Normal Keywords:
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description (last modified by Willem Van Onsem)

The idea is thus to transform code on the page like:

class Mymodel(model):
      class Meta:
           unique_together = [[ 'field1', 'field2' ]]

to:

class Mymodel(model):
      class Meta:
           constraints = [models.UniqueConstraint(fields=('field1', 'field2'), name='field1_2_unique')]

Change History (6)

comment:1 by Tim Graham, 22 months ago

Summary: The documentation on serialization uses unique_togetherUpdate serialization examples from unique_together to UniqueConstraint
Triage Stage: UnreviewedAccepted

comment:2 by Moez Saidi, 22 months ago

Owner: changed from nobody to Moez Saidi
Status: newassigned

comment:3 by Mariusz Felisiak, 22 months ago

Has patch: set
Owner: changed from Moez Saidi to Willem Van Onsem

comment:4 by Waqar Ali, 22 months ago

I believe you're confusing model meta option constratins with unique_together. UniqueConstraint is a DB constraint assigned to constraints option in Meta whereas unique together is another option on Meta level.

class Mymodel(model):
      class Meta:
           unique_together = [ 'field1', 'field2' ]
           constratints = [ UniqueConstraint ]

in reply to:  4 comment:5 by Willem Van Onsem, 22 months ago

Replying to Waqar ALi:
No, Django had in the early days unique_together, now it still has, but as the note on the documentation says (https://docs.djangoproject.com/en/4.1/ref/models/options/#django.db.models.Options.unique_together):

Use UniqueConstraint with the constraints option instead.

It "translated" to a unique constraint. But it was less flexible since one could not give it a custom name, add a condition, make it a functional unique constraint, etc. So UniqueConstraint is the "new way" to define this, whereas unique_together is the "old" way to generate such database constraint.

comment:6 by Willem Van Onsem, 22 months ago

Description: modified (diff)

The idea is thus to transform code on the page like:

class Mymodel(model):
      class Meta:
           unique_together = [[ 'field1', 'field2' ]]

to:

class Mymodel(model):
      class Meta:
           constraints = [models.UniqueConstraint(fields=('field1', 'field2'), name='field1_2_unique')]
Note: See TracTickets for help on using tickets.
Back to Top