Kendo Jaa
Kendo Jaa

Reputation: 105

How to have a many to many relation that enforces uniqueness when I use an intermediate model?

I use intermediate model for "ManyToManyField using the through"
Normally,If I don't use intermediate field, the m2m relation will be unique and can't have the duplicated data.

After I use intermediate model. the relation between m2m can have same data. like this

|    |    ['0'] (
|    |    |    addToProfile => Array (0)
|    |    |    (
|    |    |    )
|    |    |    endDate =  NULL
|    |    |    feedType =  "N"
|    |    |    id =  1
|    |    |    info =  "Big Kuy No Fear"
|    |    |    likeMaker => Array (3)
|    |    |    (
|    |    |    |    ['0'] =  "/api/v2/user/2/"
|    |    |    |    ['1'] =  "/api/v2/user/2/"
|    |    |    |    ['2'] =  "/api/v2/user/2/"
|    |    |    )
|    |    |    like_count =  "3"

I am building a social network. So this is my feed object that has 3 like_counts . But the three of this like come from the same user "/api/v2/user/2/"

I try to add "unique=True" attribute at m2m field but django come up with the error because It doesn't grant the permission to add the "unique" attribute to m2m field at first. Can anyone help me?

Upvotes: 7

Views: 11096

Answers (4)

Amin Basiri
Amin Basiri

Reputation: 184

i use this approach:

class M2MModel(models.Model):
    field1 = models.ForeignKey(Model1)
    field2 = models.ForeignKey(Model2)

    class Meta:
        constraints = [
          models.UniqueConstraint(
            fields=["field1", "field2"],
            name="each_field2_is_unique_on_each_field1",
          )
        ]

Upvotes: 0

Adrian Lopez
Adrian Lopez

Reputation: 2877

unique_together doesn't work for M2M relationships. More info.

Upvotes: 4

Chatri Sae-Tung
Chatri Sae-Tung

Reputation: 456

I just finished a feature that quite similar with your requirement but my choice is to use another simple model as an intermediate model.

Here is my code.

class Vote(models.Model):
    class Meta:
        unique_together = ['content', 'by']

    content = models.ForeignKey(Content)
    by = models.ForeignKey(User)

In my case I don't see any benefit to implement ManyToManyField.

Update: I just found from here that Django is not going to make any built-in unique together for ManyToManyField. You have to implement your own validation to make it unique.

Upvotes: 1

sneawo
sneawo

Reputation: 3631

Try to use unique_together in your intermediate model.

class M2MModel(models.Model):
    field1 = models.ForeignKey(Model1)
    field2 = models.ForeignKey(Model2)

    class Meta:
        unique_together = ('field1', 'field2')

Upvotes: 14

Related Questions