Python / Django迭代ManyToMany相关字段

时间:2014-04-10 12:25:55

标签: python django manytomanyfield related-content

我需要一些问题的帮助。

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

我现在拥有的代码是:

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,我也不知道该怎么做。非常感谢你!

1 个答案:

答案 0 :(得分:3)

你应该这样做:

for circ in self.circuit.all():