Python/Django迭代许多相关字段
我需要一些帮助来解决一个问题 我有三个模型,参考,关系和电路。关系是第一个关系的内联。电路和关系是相关的。我要做的是: -我在参考文献1中,我在关系1到关系n中选择了一些电路。 -保存时,我需要将Relation1保存到RelationN,以及其他RelationFirst(在保存参照模型时创建),后者必须包含该参照的其他关系中存在的所有回路 我现在掌握的代码是,谁不这么做呢Python/Django迭代许多相关字段,python,django,manytomanyfield,related-content,Python,Django,Manytomanyfield,Related Content,我需要一些帮助来解决一个问题 我有三个模型,参考,关系和电路。关系是第一个关系的内联。电路和关系是相关的。我要做的是: -我在参考文献1中,我在关系1到关系n中选择了一些电路。 -保存时,我需要将Relation1保存到RelationN,以及其他RelationFirst(在保存参照模型时创建),后者必须包含该参照的其他关系中存在的所有回路 我现在掌握的代码是,谁不这么做呢 class Reference(models.Model): title = models.CharField(
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)
有什么帮助吗?因为我不能迭代ManyToManyRelated字段,我也不知道怎么做。多谢各位 你应该这样做:
for circ in self.circuit.all():
具体做什么?代码的哪一部分应该更改?这如何解决OP问题?此答复中缺少一些内容。是否要为一个字符串重新发布所有代码?因此,它必须位于第3个string.No中关系类的save方法中。但是,通过查看您的帖子,您不知道正在解决什么问题。您可以说:代码中的问题是赛尔夫的circ的
。电路:
。它不起作用,因为诸如此类。。。您应该在self.circuit.all()中为circ使用:
而不是。谢谢您的建议不起作用。self.circuit.all()为空,不应为空。无论如何,谢谢你。