You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class Plan(models.Model):
name = models.CharField(max_length=50)
class PlanOption(models.Model):
name = models.CharField(max_length=50)
plan = models.ForeignKey(Plan)
If I want to generate fixtures for a Plan and a bunch of PlanOptions, I would do the following:
With this, I would expect that entry.planoption_set.all() would be populated with the generated plan options, however, even after a entry.refresh_from_db() or even reloading the plan (entry = Plan.objects.get(pk=entry.id)), entry.planoption_set.all() is still empty.
Is there a proper way to load this type of relationship?
Additional info:
When I serialize the entry with a ModelSerializer with the following attributes, the planoptions field is actually populated.
class PlanSerializer(serializers.ModelSerializer):
planoptions = serializers.SerializerMethodField()
class Meta:
model = Plan
fields = '__all__'
def get_planoptions(self, obj):
return PlanOptionSerializer(obj.planoption_set, many=True).data
This suggests that the data gets hooked up eventually, just not in the instance of the entry that has been initially created.
For now, I've opted to save the generated PlanOption records to the cls (using setUpTestData()), and compare the serialized entry (i.e. PlanSerializer(entry).data['planoptions']) with those records via an element count, and the sets of id from the serialized data and from the model list.
The text was updated successfully, but these errors were encountered:
How does one populate a reverse relationship?
Given the following models:
If I want to generate fixtures for a Plan and a bunch of PlanOptions, I would do the following:
With this, I would expect that entry.planoption_set.all() would be populated with the generated plan options, however, even after a
entry.refresh_from_db()
or even reloading the plan (entry = Plan.objects.get(pk=entry.id)
), entry.planoption_set.all() is still empty.Is there a proper way to load this type of relationship?
Additional info:
When I serialize the
entry
with a ModelSerializer with the following attributes, theplanoptions
field is actually populated.This suggests that the data gets hooked up eventually, just not in the instance of the
entry
that has been initially created.For now, I've opted to save the generated PlanOption records to the cls (using setUpTestData()), and compare the serialized
entry
(i.e.PlanSerializer(entry).data['planoptions']
) with those records via an element count, and the sets ofid
from the serialized data and from the model list.The text was updated successfully, but these errors were encountered: