[Answered ]-Specify Factory db column names with FactoryBoy in a Django Test?

1👍

The models can be improved. OP has Person and Identity models and wants that one Person corresponds to only one Identity (like a User / Person Profile). OP can achieve that with a OneToOneField. So, one can edit OP’s Identity model to

class Identity(models.Model):
    person = models.OneToOneField(Person, on_delete=models.CASCADE)

Note that I’m not using person_id. Using _id in Django Model Fields for OneToOneField and Foreign is an anti-pattern. Also, in OP’s Person model, delete the identity field since it’s not needed anymore. OP will need to run makemigrations after this.

Then, OP’s factories will get simpler

import factory
from factory import SubFactory
from factory.django import DjangoModelFactory

class IdentityFactory(DjangoModelFactory):
    person = SubFactory(PersonFactory)
     
    class Meta:
        model = Identity

Don’t forget to remove identity from PersonFactory as well.


If OP wants to keep things as they are, without many model changes, something I would advise against (but then again it depends on the goals/context), then OP can just add database='special_db' to the factories Meta, like OP mentioned here.

Leave a comment