[Answered ]-Django model A can has only one instance of model B

2👍

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'),)

Leave a comment