Wednesday, January 2, 2019

Get the list of related objects in Django

I have 3 models:

class Node(models.Model):      ID = models.DecimalField(max_digits=19, decimal_places=10)      name = models.CharField(default='node', max_length=32)      connexion = models.CharField(max_length=255)      # Many2one fields | Foreign keys:      firm = models.ForeignKey('firme.Firme', on_delete=models.CASCADE, null=True, blank=True)      class ScheduledAction(models.Model):      date = models.DateTimeField(default=datetime.now, blank=True)      firm = models.ForeignKey('firme.Firme', on_delete=models.CASCADE, null=True, blank=True)      node_ids = models.ManyToManyField(Node)

I want in ScheduledAction form to show, for a selected firm, the list of its related nodes. Normally I should do this by get:

class ScheduledActionForm(forms.ModelForm):      date = forms.DateTimeField()      firm = forms.ModelChoiceField(queryset=Firme.objects.all())      node_ids = forms.ModelMultipleChoiceField(queryset=Node.objects.get(firm_id=firm.id), widget=forms.CheckboxSelectMultiple)        class Meta:          model = ScheduledAction          fields = [              'date',              'firm',              'node_ids'          ]

But I got this error:

AttributeError: 'ModelChoiceField' object has no attribute 'id'

How can I fix this?


This is my post in StackOverFlow.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/fa7eeab7-2ee6-40c1-b648-3837bb18cdd2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment