'Django 3.2: AttributeError: 'NoneType' object has no attribute 'attname'

I am working with Django 3.2, and have come across a problem that seems to have answers here and here also, and I have tried the solutions offered in the accepted answers, but have not been able to resolve the issue I am having (error message in subject title).

Here is what my models look like:

#### models.py
class ActionableModel:

    def __init__(self, child_object):
        self.child = child_object

        # FIX: This might be an expensive operation ... need to investigate
        if isinstance(child_object, django.contrib.auth.get_user_model()):
            self.owner = child_object
            self.actionable_object = child_object
        else:
            self.owner = child_object.get_owner()
            self.actionable_object = child_object.get_actionable_object()

        self.owner_id = self.owner.id
        
        self.ct = ContentType.objects.get_for_model(self.actionable_object)
        self.object_id = self.actionable_object.id

    # ...


class Prey(models.Model):
    # ... fields
    pass


class Predator(models.Model, ActionableModel):
    catches = GenericRelation(Prey)
    catch_count = models.PositiveIntegerField(default=0, db_index=True)
    last_catch = models.DateTimeField(editable=False, blank=True, null=True, default=None)
     

    def __init__(self, *args, **kwargs):
        ActionableModel.__init__(self, *args, **kwargs)  


    # ...
    
    class Meta:
        abstract = True


# Classes used for testing - naming similar to [mommy](https://model-mommy.readthedocs.io/en/latest/basic_usage.html)
class Daddy():
    
    def __init__(self, *args, **kwargs):
        ActionableModel.__init__(self, *args, **kwargs)      





class Foo(Daddy, Predator):
    # ...
    pass

In the shell, I type the following:

from myapp.models import Foo
admin = django.contrib.auth.get_user_model().objects.all().first()
foo = Foo.objects.create(child_object=admin)

Here is the stack trace of the error that results in the subject title:

Foo.objects.create(child_object=admin)                                                                            
Traceback (most recent call last):                                                                                                            
  File "<console>", line 1, in <module>                                                                                                       
  File "/path/to/myapp/env/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method  
    return getattr(self.get_queryset(), name)(*args, **kwargs)                                                                                
  File "/path/to/myapp/env/lib/python3.8/site-packages/django/db/models/query.py", line 453, in create
    obj.save(force_insert=True, using=self.db)
  File "/path/to/myapp/env/lib/python3.8/site-packages/django/db/models/base.py", line 726, in save
    self.save_base(using=using, force_insert=force_insert,
  File "/path/to/myapp/env/lib/python3.8/site-packages/django/db/models/base.py", line 763, in save_base
    updated = self._save_table(
  File "/path/to/myapp/env/lib/python3.8/site-packages/django/db/models/base.py", line 822, in _save_table
    pk_val = self._get_pk_val(meta) 
  File "/path/to/myapp/env/lib/python3.8/site-packages/django/db/models/base.py", line 575, in _get_pk_val
    return getattr(self, meta.pk.attname)
  File "/path/to/myapp/env/lib/python3.8/site-packages/django/db/models/query_utils.py", line 148, in __get__
    val = self._check_parent_chain(instance)
  File "/path/to/myapp/env/lib/python3.8/site-packages/django/db/models/query_utils.py", line 164, in _check_parent_chain
    return getattr(instance, link_field.attname)
AttributeError: 'NoneType' object has no attribute 'attname'

What is causing this error, and how can I resolve it?



Solution 1:[1]

The problem seems to be that the __init__ method from the django Model class never gets called. This is because an __init__ method is defined in your derived class, but the super() method is not called explicitly.

Two things are needed:

  • Setting up a chain of super calls.
  • Ensuring the method resolution order allows the chain of super to reach the Model.__init__ method.

Applying these points to the source code provided:

class ActionableModel:

    def __init__(self, child_object, *args, **kwargs):
        # need to call super here
        super().__init__(*args, **kwargs)
        self.child = child_object
        ...


class Prey(models.Model):
    pass


class Predator(ActionableModel, models.Model):
    catches = GenericRelation(Prey)
    ...    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)  


class Daddy:        
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)      


class Foo(Daddy, Predator):
    pass

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1