1

I need some help with an issue.

I have three models, Reference, Relation ans Circuit. Relation is an inline of the first one. Circuit and Relation are related. What I have to do is: - I'm in Reference 1 and I have selected some Circuits inside my Relation1 to RelationN. - When I save, I need to save Relation1 to RelationN, and other RelationFirst (created when the Reference model is saved) who must contain all the Circuits that exist in the other Relations of that Reference.

The code that I have right now, who doesn't do it, is:

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)

Any help? Because I can't iterate the ManyToManyRelatedField, and I don't know how to do it. Thank you very much!

1 Answers1

3

You should do it that way:

for circ in self.circuit.all():
Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43
  • 1
    do what exactly? Which portion of the code should be changed? How does that resolve the OP issue? These are few things missing in this reply. – UmNyobe Apr 10 '14 at 12:55
  • You want to repost all the code for one string? So it have to be in save method of Relation class in 3th string. – Eugene Soldatov Apr 10 '14 at 12:57
  • No. but by looking at your post there is no clue about what is being resolved. you can say: the issue in your code is `for circ in self.circuit:`. It doesnt work because blah blah blah... you should use `for circ in self.circuit.all():` instead – UmNyobe Apr 10 '14 at 12:59
  • Not working. self.circuit.all() is empty, and it shouldn't be. Anyway, thank you. – user3350963 Apr 10 '14 at 13:25