如何将ForeignKey-Djang上的引用设置为空

2024-05-08 14:37:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始学Python和Django,我想做一些非常简单的事情,但是经过几个小时的搜索,我还没有找到答案,所以我的问题来了:

我要模型:用户(CustomUser)和房子。

我想在User中有一个字段引用一个房子,这个字段可以是可选的,模拟一个人可以在房子的内部(当引用被附加时)或外部(当它为空时)。 在House模型中,我还希望有一个“列表”,其中列出了在某个特定时刻在屋内的人(用户)。

为了达到这个目的,我做了这样的事情:

class User(AbstractBaseUser):
 # other attrs ...

 # (ForeignKey) house: House where the user is right now
 house = models.ForeignKey(House,
  verbose_name='where is the user right now',
  related_name='house_now', blank=True, null=True,
  on_delete=models.SET_NULL
 )
 def leaveHouse(self):
    house = self.house.delete()

class House(models.Model):
 # (ManyToManyField) people: List of Users that are currently within the house
 people = models.ManyToManyField(settings.AUTH_USER_MODEL,
           verbose_name='people inside the house right now',
           related_name='people',
           blank=True
        )

 def removeUser(self, user):
  self.people.remove(user)

问题是,当我使用用户模型的leafHouse函数时,它不会将ForeignKey设置为Null或空,而是删除引用该键的House对象。

有什么关于我做错了什么的建议,最佳实践之类的吗?

提前谢谢!

编辑:

不管怎样,只是一个与此相关的小问题。 为什么在django管理员中,如果我将字段“house”设置为“-”(无)工作正常,但如果我将字段“home”设置为“-”,则会给我 “'NoneType'对象没有'pk'属性”

# (ForeignKey) home: Main house
    home = models.ForeignKey(House,
        verbose_name='default house',
        related_name='home', blank=True, null=True,
        on_delete=models.SET_NULL
    )

Tags: the用户name模型selftruehomemodels