Question

I'm using model_mommy with Django tests to create objects. I'm having trouble creating a model with a reverse FK. I can do it the opposite way round as a workaround, but whilst it works it doesn't look right so I wonder if I can do it the other way round?

Say I have two models, User and Profile, related via an FK from Profile to User (it's not a one to one, it's just an FK). The Profile model has a bool attribute call is_aardvark.

In model mommy I can create recipes like so:

aardvark_profile = Recipe(Profile, is_aardvark=True)
non_aardvark_profile = Recipe(Profile, is_aardvark=False)

Then I can create a User with an aardvark profile in my test with something like:

user = mommy.create_recipe(aardvark_profile).user

This doesn't seem right, as I'm creating a user via the aardvark_profile recipe. I want to create a User via some sort of User recipe ideally (maybe in future I'll have some other model FKd to User, so the above wouldn't work).

I've tried things like the below, which doesn't work:

# doesn't work
broken_aardvark_user = Recipe(User, profile_set=mommy.create_recipe(aardvark_profile)

Is this even possible? Any ideas? I could just create a helper method to do this for me if all else fails.

Thanks!

Was it helpful?

Solution

You could do this:

from model_mommy.recipe import Recipe, related

aardvark_profile = Recipe(Profile, is_aardvark=True)
aardvark_user = Recipe(User, profile_set=related('aardvark_profile'))

Hope it helped

[1] http://model-mommy.readthedocs.org/en/latest/recipes.html#recipes-with-foreign-keys

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top