Home > database >  How can I mock django model object?
How can I mock django model object?

Time:01-22

For example, I have many interrelated tables in my project

class A(models.Model):
    name = models.models.CharField(max_length=16)

class B(models.Model):
    name = models.models.CharField(max_length=16)
    a = models.ForeignKey(A, on_delete=models.CASCADE)

class C(models.Model):
    name = models.models.CharField(max_length=16)
    b = models.ForeignKey(B, on_delete=models.CASCADE)

and so on.

I need to test model C and have no interest in A and B models. Is there any chance to mock model B that can be used when creating model C objects? I mean I'd like to create few objects without building a massive test base to test one tiny model.

CodePudding user response:

If it is only for some tests and you only need a few instances you could do something like this:

model_a_instance = A(name='somename')
model_b_instance = B(name='somename2', a=model_a_instance)
model_c_instance = C(name='somename3', b=model_b_instance)

Nonetheless, if you need to save model_c in the DB make sure to save model_a and model_b also.

If you are going to need these models more extensively I would recommend creating a factory class to populate your models.

Hopefully this helped.

CodePudding user response:

you can use bakery

from model_bakery import baker
AmodelInstance = baker.make(A)
  •  Tags:  
  • Related