'NoneType'对象没有属性'add'

时间:2018-11-29 21:44:43

标签: python django django-models

我有以下User对象,

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)

我有以下课程来管理连接,

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,
    )

当我尝试添加朋友时,

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)

出现以下错误,

'NoneType' object has no attribute 'add'

有人可以帮我吗?

2 个答案:

答案 0 :(得分:3)

您似乎正在尝试使用django related manager add function

sender_connections.friends.add(receiver)

但是,连接上的friends属性是ForeignKey关系而不是ManyToManyField。这意味着当您呼叫sender_connections.friends并且连接不存在时,您将获得“无”。

如果将属性更改为ManyToManyField,则sender_connections.friends将返回ManyRelatedManager,并且添加应按预期工作。

答案 1 :(得分:0)

补充 wingardtw 答案,在Django 3.0中,您可以使用PrimaryKeyRelatedField,而不是使用“ add”,而是对queryset进行更新,例如:

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

重要提示:这要求对象已保存。

有关更多信息,请参见那些链接:

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