简体   繁体   中英

django many to many association

How do I create the association in MyListAssoc from here? How would I delete it?

class Group(models.Model):
    name = models.CharField(max_length=32, unique=True)
    def __unicode__(self):
        return '%s %s' % (self.name)

class MyKeywords(models.Model):
    name = models.CharField(max_length=32, unique=True)
    def __unicode__(self):
        return self.name

class MyListAssoc(models.Model):    
    group = models.ForeignKey(Group)
    keyword = models.ManyToManyField(MyKeywords)

mygroup = Group.objects.get(name="mygroup")
mykeyword = MyKeywords.objects.create(name="mykeyword")

You just need a many to many relation, something like:

class Group(models.Model):
    name = models.CharField(max_length=32, unique=True)
    keywords = models.ManyToManyField(MyKeywords)

    def __unicode__(self):
        return '%s' % (self.name)

class MyKeywords(models.Model):
    name = models.CharField(max_length=32, unique=True)

    def __unicode__(self):
            return self.name

Then, you can use your m2m relation:

group = Group.objects.get(name='something')
keyw = MyKeywords.objects.get(name='something_else')
group.keywords.add(keyw)
group.keywords.all()
group.keywords.remove(keyw)

NOTE : It is recommended that the name of a class is in singular, so it should be MyKeyword instead of MyKeywords

mygroup = Group.objects.get(name="mygroup")
mykeyword = MyKeywords.objects.create(name="mykeyword")

mylistassoc = MyListAssoc(group=mygroup)
mylistassoc.save()
mylistassoc.keyword.add(mykeyword) 

If you want to remove the association, just use remove(mykeyword) instead of add(mykeyword) .

However, you don't need intermediary model at all to set the relation between groups and keywords.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM