Best practice on deep relationships

34 views
Skip to first unread message

dbin...@gmail.com

unread,
May 19, 2016, 12:18:30 PM5/19/16
to Factory Boy
Greetings, I have a schema with many relationships. What is the best practice on using factory_boy in this situation?

For instance, say I have the following:

A has many B has many C has many D. AND
B has many E has many F


In this circumstance, were I to try to create an object F (using SubFactories for all parent objects) I'll get an error saying that A already exists (due to unique constraints; i want one true parents).

Now I can run a setUp such that I simply pass down the parents all the way through the tree, but that seems like a lot of non-DRY work for each test case. Is there a best practice here?

Thanks

conrad....@oxfordbiodynamics.com

unread,
Jul 8, 2016, 11:34:55 AM7/8/16
to Factory Boy, dbin...@gmail.com
bump!

Raphaël Barrois

unread,
Jul 8, 2016, 2:08:23 PM7/8/16
to Factory Boy
Hi,

If you want to enforce uniqueness constraints on A, you should use http://factoryboy.readthedocs.io/en/latest/orms.html#factory.django.DjangoOptions.django_get_or_create or a similar implementation.

This way:
- The first F will create its E, B, A
- The second one will create its E, B, reuse the existing A

If you're using other ORMs, handling the uniqueness of A per A.some_unique_field can be achieved by overriding A's _create() function,
akin to DjangoModelFactory: https://github.com/rbarrois/factory_boy/blob/master/factory/django.py#L150,L181

--
Raphaël

Reply all
Reply to author
Forward
0 new messages