Melissa Stewart
Melissa Stewart

Reputation: 3605

'NoneType' object has no attribute 'add'

I have the following User object,

class User(AbstractBaseUser, PermissionsMixin, Base):
    username = models.CharField(
        db_index=True, 
        null=False, 
        unique=True,  
        max_length=255,
    )
    mobile = PhoneNumberField(
        db_index=True,  
        null=False,  
        unique=True,
    )
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)

And I've the following class to manage connections,

class Connections(Base):
    owner = models.OneToOneField(
        User, 
        on_delete=models.CASCADE,
        null=True,
    )
    friends = models.ForeignKey(
        User, 
        on_delete=models.CASCADE,
        related_name='friend_set',
        null=True, 
        blank=True,
    )
    followers = models.ForeignKey(
        User, 
        on_delete=models.CASCADE,
        related_name='follower_set',
        null=True, 
        blank=True,
    )
    followings = models.ForeignKey(
        User, 
        on_delete=models.CASCADE,
        related_name='following_set',
        null=True, 
        blank=True,
    )

When I try to add a friend,

sender = User.objects.get(
    id=kwargs.get('sender_id')
)
receiver = User.objects.get(
    id=kwargs.get('receiver_id')
)
sender_connections, created =(
    Connections.objects.get_or_create(owner=sender)
)
sender_connections.friends.add(receiver)

I get the following error,

'NoneType' object has no attribute 'add'

Can someone help me with this?

Upvotes: 2

Views: 2040

Answers (2)

Júlio Reis
Júlio Reis

Reputation: 336

Complementing the wingardtw answer, with Django 3.0 you can use PrimaryKeyRelatedField, and instead of using "add" you will perform an update on the queryset, like under:

Connections.objects.filter(owner=sender).update(friends=receiver)

Important: This requires the objects to already be saved.

See those link for more information:

https://docs.djangoproject.com/en/3.0/ref/models/relations/#django.db.models.fields.related.RelatedManager.add

https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.update

Upvotes: 1

wingardtw
wingardtw

Reputation: 143

It looks like you are trying to user the django related manager add function

sender_connections.friends.add(receiver)

However the friends attribute on connections is a ForeignKey relation instead of a ManyToManyField. This means that when you call sender_connections.friends and the connection does not exist, you will get None.

If you change the attribute to a ManyToManyField, then sender_connections.friends will return a ManyRelatedManager and the add should work as expected.

Upvotes: 5

Related Questions