简体   繁体   English

反向FK模型妈妈食谱

[英]Model Mommy Recipe with Reverse FK

I'm using model_mommy with Django tests to create objects. 我在Django测试中使用model_mommy创建对象。 I'm having trouble creating a model with a reverse FK. 我在创建带有反向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). 假设我有两个模型,即用户和个人资料,通过个人资料与用户之间的FK关联(不是一对一,而是FK)。 The Profile model has a bool attribute call is_aardvark. Profile模型具有bool属性调用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: 然后,我可以在测试中使用类似aardvark的个人资料创建一个User:

user = mommy.create_recipe(aardvark_profile).user

This doesn't seem right, as I'm creating a user via the aardvark_profile recipe. 这似乎不对,因为我是通过aardvark_profile配方创建用户的。 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). 我想理想地通过某种用户配方创建一个用户(也许将来我会向用户提供其他模型FKd,所以上述方法不起作用)。

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! 谢谢!

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 [1] http://model-mommy.readthedocs.org/en/latest/recipes.html#recipes-with-foreign-keys

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM