Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set to null the reference on a ForeignKey - Django

Tags:

python

django

I've just started in Python and Django and I'm trying to do something pretty easy, but after many hours searching I haven't found the answer, so here it comes my question:

I have to Models: User (CustomUser) and House.

I want to have a field in User that references a House and that can be optional, emulating the fact that a person can be inside (when a reference is attached) or outside (when it's null) a house. In the House model, I want to have also a "list" of people (Users) that are at a given moment inside the house.

To accomplish this, I've done something like this:

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)

The problem is that when I use the function leaveHouse of the User model, instead of setting the ForeignKey to Null or Empty, it deletes the House object referenced to the key.

Any suggestion on what I'm doing wrong, best practices and that kind of stuff please?

Thanks in advance!

EDIT:

Anyway, just a little question related to this. Why in the django admin if I set the field "house" as "----" (None) works fine, but if I set the field "home" as "----" gives me "'NoneType' object has no attribute '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
    )
like image 245
Guillermo López Avatar asked Apr 03 '16 12:04

Guillermo López


1 Answers

Instead of deleting the related house object, set the link value to None:

self.house = None
self.save()
like image 110
alecxe Avatar answered Nov 19 '22 13:11

alecxe