[Solved]-Django: one-to-one field with factory_boy: UNIQUE constraint failed


The problem was that CourseFactory() already creates a CourseInfo object. I’ve resolved this by just removing the info = factory.RelatedFactory(CourseInfoFactory, 'course') line, and now the CourseInfoFactory is unnecessary – I can test CourseInfo by getting the created object at course.info.



Just add the django_get_or_create in the Meta class of your CourseInfoFactory:

class Meta:
    django_get_or_create = ('group',)

This solution avoids the problem of a unique constraint in your field, and creates it if exists.

You could check here: https://github.com/FactoryBoy/factory_boy/blob/v2.5.2/factory/django.py#L133-L139

Leave a comment