Django如何填充' trough'将对象添加到ManyToManyField时的中间模型?

时间:2016-11-21 18:40:49

标签: python django django-models many-to-many

我无法正确说出来,也无法在文档中找到它,但我如何添加到中间版'通过'向其添加新对象时ManyToManyField的模型?

请注意,它是一种递归关系,但我使用ManyToMany,因为我不确定OneToOne是否支持"通过" model(文档没有指定)

无论Person_Person字段如何,都将使用curr_partner,向其中添加父/子关系等对象(Person中没有字段) (这是因为ManyToManyField是SQL关系数据库中输出表中的实际字段的混淆)

(我意识到我的模型存在一些上下文/理论上的缺陷,但现在让我们抽象出来)

例如

Models.py:

class Person(models.Model):
    objectid = models.AutoField(primary_key=True)
    name = models.CharField()
    curr_partner = models.ManyToManyField(
        self, 
        on_delete = models.CASCADE, 
        through = Person_Person, #This lets you define the model that will act as an intermadiary
        symmetrical = False, #This needs to be set with recursive relationships
    )

class Person_Person(models.Model):
    person_1 = models.ForeignKey(Person, ondelete=models.CASCADE)
    person_2 = models.ForeignKey(Person, ondelete=models.CASCADE)
    relation = models.ChoiceField(            
        ('P', 'Parent'),
        ('C', 'Child'),
        ('E', 'Engaged'),
        ('W', 'Widow'),
    )

查询:

#Adding a married couple

father = Person(name = "John")
mother = Person(name = "Anna")

father.curr_partner.add( mother , through.relation = "Engaged") #???

#Adding a 'Child' relation

child = Person(name = "Billy")

#This makes sense??
p1 = Person_Person(person1 = father, person2 = child, relation = "Child")
p2 = Person_Person(person1 = mother, person2 = child, relation = "Child")

1 个答案:

答案 0 :(得分:1)

您可以通过保存关系模型的实例来创建关系,就像您(几乎)对孩子一样。你有像

这样的东西
public class AddressModel : IValidatableObject
{
    [Required]
    public string Country { get; set; }
    public string State { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if(Country == "United States" && String.IsNullOrEmpty(State))
        {
            yield return new ValidationResult("State is required for United States", new [] { nameof(State) });
        }
    }
}
顺便说一句,您的father = Person(name = "John") mother = Person(name = "Anna") marriage = Person_Person.objects.create(person1=father, person2=mother, relation="E") p1 = Person_Person.objects.create(person1=father, person2=child, relation="C") p2 = Person_Person.objects.create(person1 = mother, person2 = child, relation="C") 属性没有准确的名称,因为它实际上表示了所有人的关系,而不仅仅是婚姻。也许您应该将其重命名为curr_partnerrelationships并拥有一个属性来获取此人的合作伙伴:

kindred