fcurella / django-fakery

🏭 An easy-to-use implementation of Creation Methods for Django, backed by Faker.
http://django-fakery.readthedocs.org/en/stable/
MIT License
115 stars 6 forks source link

Passing kwargs to related models #55

Open sobolevn opened 4 years ago

sobolevn commented 4 years ago

Imagine that we have a model like so:

class User(models.Model):
     profile = models.ForeignKey('UserProfile') 
     is_active = models.BooleanField()

And later I want to use it like so:

active_user_factory = fakery.blueprint(User).fields(
    is_active=True,
)

empty_username = active_user_factory.m(profile__username='')
email_username = active_user_factory.m(profile__username='email@example.com')

But, currently this does not work. What can be done to pass kwargs to related objects?

fcurella commented 4 years ago

Hi @sobolevn

I'm not entirely sure a FK from User to Profile is what you want in the first place. It means that potentially more than one User can point to the same Profile instance.

What you probably want is either a OneToOneField (so each User has exactly one Profile and vice-versa), or a FK from Profile to User (ie: a User can have multiple Profiles).

sobolevn commented 4 years ago

Well, that's just an example 🙂

fcurella commented 4 years ago

Blueprints can use other blueprints as values for their fields.

I would try something this:

user_factory = fakery.blueprint(User).fields(is_active=True)
profile_factory = fakery.blueprint(Profile).fields(user=user_factory)

empty_username = profile_factory.m(username='')
email_username = profile_factory.m(username='email@example.com')

Keep in mind that this will create a different user on your database every time you call profile_factory, so you'll end up with 2 users.