Django's ManyToMany Relationship with Additional Fields

前端 未结 1 909
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 22:03

I want to store some additional information in that, automatically created, ManyToMany join-table. How would I do that in Django?

In my case I have two tables: \"Em

相关标签:
1条回答
  • 2020-12-07 22:29

    Here is example of what you want to achieve:

    http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships

    In case link ever breaks:

    from django.db import models
    
    class Person(models.Model):
        name = models.CharField(max_length=128)
    
        def __str__(self):              # __unicode__ on Python 2
            return self.name
    
    class Group(models.Model):
        name = models.CharField(max_length=128)
        members = models.ManyToManyField(Person, through='Membership')
    
        def __str__(self):              # __unicode__ on Python 2
            return self.name
    
    class Membership(models.Model):
        person = models.ForeignKey(Person)
        group = models.ForeignKey(Group)
        date_joined = models.DateField()
        invite_reason = models.CharField(max_length=64)
    
    0 讨论(0)
提交回复
热议问题