How to make recursive ManyToManyField relationships that have extra fields symmetrical in Django?

前端 未结 5 743
后悔当初
后悔当初 2020-12-18 07:53
class Food_Tag(models.Model):
    name = models.CharField(max_length=200)
    related_tags = models.ManyToManyField(\'self\', blank=True, symmetrical=False, through=         


        
5条回答
  •  一生所求
    2020-12-18 08:30

    To create a symmetrical relationship, you have two options:

    1) Create two Tag_Relation objects - one with steak as the source, and another with steak as the target:

    >>> steak = Food_Tag.objects.create(name="steak")
    >>> meat = Food_Tag.objects.create(name="meat")
    >>> r1 = Tag_Relation(source=steak, target=meat, is_a=True)
    >>> r1.save()
    >>> r2 = Tag_Relation(source=meat, target=steak, has_a=True)
    >>> r2.save()
    >>> steak.related_tags.all()
    []
    >>> meat.related_tags.all()
    [

    2) Add another ManyToManyField to the Food_Tag model:

    class Food_Tag(models.Model):
        name = models.CharField(max_length=200)
        related_source_tags = models.ManyToManyField('self', blank=True, symmetrical=False, through='Tag_Relation', through_fields=('source', 'target'))
        related_target_tags = models.ManyToManyField('self', blank=True, symmetrical=False, through='Tag_Relation', through_fields=('target', 'source'))
    
    class Tag_Relation(models.Model):
        source = models.ForeignKey(Food_Tag, related_name='source_set')
        target = models.ForeignKey(Food_Tag, related_name='target_set')
    

    As a note, I'd try to use something more descriptive than source and target for your through model fields.

提交回复
热议问题