Skip to content Skip to sidebar Skip to footer

Django Model Unique Together Both Ways

Many questions already on this topic, but not what i'm searching for. I have this Model: class Options(TimeStampedModel) option_1 = models.CharField(max_length=64) option_2

Solution 1:

I think a ManyToMany relation with a custom through table and an unique_together constraint on that table should do what you want.

Example code:

from django.db.models import Model, ForeignKey, ManyToManyField, CharField

class Option(Model):
    name = CharField()

class Thing(TimeStampedModel):
    options = ManyToManyField("Option", through="ThingOption")    

class ThingOption(Model):
    thing = ForeignKey(Thing)
    option = ForeignKey(Option)
    value = CharField()

    class Meta:
        unique_together = ('thing', 'option')

For Django 2.2+ it is recommended to use UniqueConstraint. In the docs there is a note stating unique_together may be deprecated in the future. See this post for its usage.

Solution 2:

You can override create method, do something like

from django.db import models

classMyModelManager(models.Manager):
    defcreate(self, *obj_data):
        # Do some extra stuff here on the submitted data before saving...       # Ex- If obj_data[0]=="eggs" and obj_data[1]=="spam" is True don't allow it for your blah reason      # Call the super method which does the actual creationreturnsuper().create(*obj_data) # Python 3 syntax!!classMyModel(models.model):
    option_1 = models.CharField(max_length=64)
    option_2 = models.CharField(max_length=64)

    objects = MyModelManager()

Post a Comment for "Django Model Unique Together Both Ways"