mrsolupo
mrsolupo

Reputation: 181

Django model A can has only one instance of model B

I have two models:

class ModelA(models.Model):
    name = models.CharField(max_length=256)

class ModelB(models.Model):
    user = models.ForeignKey(MyUser)
    model_a = models.ForeignKey(ModelA)
    points = models.IntegerField(default=0)

How can I prevent creating the same object? For example:

I have A, B, C instances of ModelA, and two users. In ModelB I need relationships like this:

User1 can has only one 'link' to A, one to B, etc. User2 the same. He can only one 'link' to each ModelA instance.

Each User can has one record in ModelB associated with ModelA.

E.g. (User1, A, 100), (User2, A, 50) But if I will try to do something like this

...create(user=User1, model_a=A, points=50)

I need to get from db records with user1, and A, and ad points, not creating another similiar model.

Upvotes: 1

Views: 307

Answers (1)

Roman Sobkuliak
Roman Sobkuliak

Reputation: 56

So you want all pairs of user and model_a to be unique. You can specify this in the metadata of the model using unique_together.

unique_together = (("driver", "restaurant"),)

This is a tuple of tuples that must be unique when considered together. It’s used in the Django admin and is enforced at the database level (i.e., the appropriate UNIQUE statements are included in the CREATE TABLE statement).

Django documentation - unique_together

Therefore modify your model in following way:

class ModelB(models.Model):
    user = models.ForeignKey(MyUser)
    model_a = models.ForeignKey(ModelA)
    points = models.IntegerField(default=0)

    class Meta:
        unique_together = (('user', 'model_a'),)

Upvotes: 2

Related Questions