Michael Wiles
Michael Wiles

Reputation: 21186

How to embed a filter in the other side of a foreign key relationship in django

I have the following structure:

class Room(models.Model):
    doors: BaseManager

class Door(models.Model):
    deleted = models.BooleanField(default=False)
    room = models.ForeignKey(to=Room, related_name='doors'
)        

Now after I've saved a room and saved some doors which reference that room I can load a room and get all the doors in the room...

However, when I do a room.doors.all() I actually want to receive only those doors that are not deleted (that have deleted as false).

How would you do this with django?

UPDATE: Sorry, I wasn't quite clear in terms of what I wanted...

I want this behaviour: Once I have an instance of room and I go fetch the doors linked to that room with room.doors.all() - at this point I only want doors that are not deleted.

Upvotes: 0

Views: 65

Answers (1)

Samyak Jain
Samyak Jain

Reputation: 367

Add this line in your Door model first:

STATUS_CHOICES = (
        ('deleted', 'deleted'),
        ('not_deleted', 'not_deleted'),
    )

Then, edit your deleted model field to this:

deleted = models.CharField(max_length=1o,choices=STATUS_CHOICES)

Then, you can access the doors that are not deleted with:

Door.not_deleted.all()

Upvotes: 1

Related Questions