Search code examples
pythondjangotestingfaker

Clone model field created with Django faker inside DjangoModelFactory


I use Django Faker to generate ramdom data and it works great.

I need to check in a model that two fields responsible and customer in a peculiar situation are identical.

Here is my factory class:

class FirstQuoteRequest(DjangoModelFactory):

    label = Faker("sentence")
    description = Faker("sentences")
    customer = SubFactory(UserFactory)
    responsible = customer

By typing responsible = customer, I thought I'd add a clone of customer value but in this case, it's a clone of the function that returns a ramdom value which is not what I want.

I thought of using @post_generation like this:

    @post_generation
    def responsible(self, create: bool, extracted: Sequence[Any], **kwargs):
        self.responsible = self.customer
        self.save()

But it raises an Integrity error. Is it a way to have this equalization between customer and responsible? Which one?


Solution

  • The issue came from the name of my method which shouldn't be equal to the field name. So the solution is:

    class FirstQuoteRequest(DjangoModelFactory):
    
        label = Faker("sentence")
        description = Faker("sentences")
        customer = SubFactory(UserFactory)
        responsible = customer
    
        @post_generation
        def clone_customer(self, create: bool, extracted: Sequence[Any], **kwargs):
            self.responsible = self.customer
            self.save()
    

    Hope, it helps!