我需要一些帮助。

我有三种模型,参考,关系和电路。关系是第一个关系。电路和关系是相关的。我要做的是:
-我在参考1中,并且在Relation1到RelationN中选择了一些电路。
-保存时,我需要将Relation1保存到RelationN,并将另一个RelationFirst(保存参考模型时创建)保存到该ReferenceFirst,其中必须包含该参考的其他关系中存在的所有电路。

我现在没有执行的代码是:

class Reference(models.Model):
    title = models.CharField(max_length=200, verbose_name = _('title'))

    def __unicode__(self):
        return u"\n %s" %(self.title)

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
        is_new = self.id is None
        super(Reference, self).save(force_insert, force_update, *args, **kwargs)
        if is_new:
            Relation.objects.create(reference=self, first = True)
            relation = Relation.objects.get(reference=self, first = True)
            circuit = Circuit.objects.get(name = '0')
            relation.circuit.add(circuit)


class Relation(models.Model):
    first = models.BooleanField()
    reference = models.ForeignKey(Reference)
    circuit = models.ManyToManyField('Circuit', verbose_name = _('Circuits'), null=True, blank=True, related_name = 'relation_circuit')

    def __unicode__(self):
        return u"%s" %(self.reference)

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
        relation1 = Relation.objects.get(reference=self.reference, first = True)
        super(Relation, self).save(force_insert, force_update, *args, **kwargs)
        for circ in self.circuits:
            circuit = Circuit.objects.get(pk = circ)
            relation1.circuit.add(circuit)


有什么帮助吗?因为我无法迭代ManyToManyRelatedField,而且我也不知道该怎么做。非常感谢你!

最佳答案

您应该这样做:

for circ in self.circuit.all():

关于python - Python/Django迭代ManyToMany相关字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22988026/

10-12 01:10