Nebulosar
Nebulosar

Reputation: 1855

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 = models.CharField(max_length=64)

    class Meta:
        unique_together = ('option_1', 'option_2')

Now I have a unique constraint on the fields. Is there a way to also define this the other way around so that it doesn't matter what was option_1 and what was option_2

As example:

Options.create('spam', 'eggs') # Allowed
Options.create('spam', 'eggs') # Not allowed
Options.create('eggs', 'spam') # Is allowed but should not be

Thanks in advance!

Upvotes: 6

Views: 5731

Answers (2)

etene
etene

Reputation: 728

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.

Upvotes: 7

ramganesh
ramganesh

Reputation: 811

You can override create method, do something like

from django.db import models

class MyModelManager(models.Manager):
    def create(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 creation
        return super().create(*obj_data) # Python 3 syntax!!

class MyModel(models.model):
    option_1 = models.CharField(max_length=64)
    option_2 = models.CharField(max_length=64)

    objects = MyModelManager()

Upvotes: 1

Related Questions