Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 592
Kendo Jaa Avatar asked Feb 07 '13 14:02

Kendo Jaa


2 Answers

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')
like image 176
sneawo Avatar answered Sep 21 '22 11:09

sneawo


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

like image 24
Adrian Lopez Avatar answered Sep 22 '22 11:09

Adrian Lopez