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

时间:2016-04-03 12:53:28

标签: python django

我刚刚开始使用Python和Django而且我正在尝试做一些非常简单的事情,但经过几个小时的搜索后我还没有找到答案,所以这就是我的问题:

我需要模特:用户(CustomUser)和House。

我想在User中有一个引用House的字段,它可以是可选的,模仿一个人可以在里面(当一个引用被附加时)或外面(当它为null时)一个房子。 在众议院模型中,我想要在房子内的某个特定时刻有一个“人员(用户)”列表。

要做到这一点,我做了类似的事情:

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)

问题在于,当我使用User模型的函数leaveHouse时,不是将ForeignKey设置为Null或Empty,而是删除引用该键的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
    )

1 个答案:

答案 0 :(得分:8)

不要删除相关的house对象,而是将链接值设置为None

self.house = None
self.save()