Search code examples
djangodjango-rest-frameworkdjango-testingdjango-testsfactory-boy

Django Model Object has no attribute '_default_manager' when using factory boy


I am using Django Rest Framework to create some api's. I am using factory boy to create test instances. I have an Abstract model called base_model which is inherited by all other models of the project.

    created_at = models.DateTimeField(editable=False)
    updated_at = models.DateTimeField(editable=False)

    class Meta:
        abstract = True
        ordering = ['id']

    def save(self, *args, **kwargs):
        if not self.created_at:
            self.created_at = timezone.now()
        self.updated_at = timezone.now()
        super(BaseModel, self).save(*args, **kwargs)

My client Model

 from django.db import models

from mtl_manager.api.base_model import BaseModel
from mtl_manager.projects.enums import ProjectStatus
 
class Client(BaseModel):
    client_name = models.CharField(max_length=250, blank=False)
    phone_number = models.CharField(max_length=250, blank=False)
    email = models.EmailField(blank=False, unique=True, null=False)
    addressLane1 = models.TextField()

This model worked. I was able to create retrieve and list client objects . Now I was about to unit test the routes and started with creating instance using Factory boy

class ClientFactory(DjangoModelFactory):
    name = Faker("company")
    gst = "323232";
    phone_number = Faker("phone_number")
    zipCode = "686542"
    address_lane = Faker("street_address")
    registration_number = "32313094839483"
    state = "kerala"
    country = Faker("country")

    class Meta:
        model = Client()

This raises error Attribute-error: 'Client' object has no attribute '_default_manager'.

But from my console I verified if client has default manager using

In [11]: Client.objects
Out[11]: <django.db.models.manager.Manager at 0x7fe4fc6d7bb0>

Solution

  • You need to pass a reference to the Client class, not construct a Client object, the parenthesis in model = Client() thus should be removed:

    class ClientFactory(DjangoModelFactory):
        # …
    
        class Meta:
            model = Client