Factory_boy objects seem to be missing primary keys

When I create factory_boy objects, the object does not have a primary key, and I'm not sure why. Here is my model and factory:

# models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): # UserProfile is a subset table of User. They have a 1:1 relationship. user = models.ForeignKey(User, unique=True) gender = models.CharField(max_length=1) # factories.py import factory from django.contrib.auth.models import User from .models import UserProfile class UserFactory(factory.Factory): FACTORY_FOR = User username = 'jdoe' class UserProfileFactory(factory.Factory): FACTORY_FOR = UserProfile user = factory.lazy_attribute(lambda a: UserFactory()) gender = 'M' 

Now, according to the factory_boy documentation on associations, if I create a user instance, I should get the id field. However, I do not. This is what I get (in the interpreter):

 >>> from app.factories import UserFactory, UserProfileFactory >>> user = UserFactory() >>> user.username # This result is correct 'jdoe' >>> user.id is None # User should be 'saved' and so this should return False True 

Similarly:

 >>> user_profile = UserProfileFactory() >>> user_profile.gender # This is OK 'M' >>> user_profile.user # This is OK <User: jdoe> >>> user_profile.id is None # Why isn't this False? True 

The documentation states that these user.id and user_profile.id commands should return “False” instead of “True”, since I am creating factory_boy instances (as opposed to assembly). What am I missing here? Why am I not getting the id value when I create these instances? It seems that the only way to get the identifier is to explicitly create the id attribute in my factories. However, I don’t see this in the documentation, so I don’t think what you should do.

Thanks.

+6
source share
2 answers
+15
source

For completeness, it is also worth noting that in order to explicitly save the factory in the database, the documentation says that you can use:

 user = UserProfile.create() 

which does the same as the following if you use a subclass of DjangoModelFactory:

 user = UserProfile() 

Only when objects are stored in the database do they receive PK.

To create a factory and not explicitly save it to the database, use:

 user = UserProfile.build() 
+4
source

Source: https://habr.com/ru/post/954432/


All Articles