Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to populate a reverse relationship? #105

Open
rhelms opened this issue Jan 11, 2018 · 0 comments
Open

How to populate a reverse relationship? #105

rhelms opened this issue Jan 11, 2018 · 0 comments

Comments

@rhelms
Copy link

rhelms commented Jan 11, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant