many to many relation does't be unique when I use intermediate model.

Kendo Jaa picture Kendo Jaa · Feb 7, 2013 · Viewed 7.2k times · Source

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_count s . 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 does't grant the permission to add the "unique" attribute to m2m field at first. Can anyone help me

Answer

sneawo picture sneawo · Feb 7, 2013

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