django-autofixture
django-autofixture copied to clipboard
How to populate a reverse relationship?
How does one populate a reverse relationship?
Given the following models:
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:
fixture = AutoFixture(Plan)
entry = fixture.create_one()
fixture = AutoFixture(PlanOption, field_values={
'plan': generators.InstanceSelector(Plan, limit_choices_to={'pk': entry.pk})
})
fixture.create(10)
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.