Activate and Deactivate Boolean Django

I have this first model called "People", which has an attribute called "State" that is of type Boolean, this model I call in the model "Birthday". What I want is that when a person is inactive in their "State", they disappear from the "Birthday" model, and that when they are activated again, they appear in the "Birthday" model.

It should be noted that in the Django administrative panel, when I enter the "birthday" model, all the people registered in the "People" model are displayed, even if they are active or not due to their "State" (Boolean). Maybe it could be solved with a condition.

class People(models.Model):
   Name = models.CharField('Name', max_length = 20, blank = False, null = False)
   Last_Name = models.CharField('Last Name', max_length = 20, blank = False, null = False)
   State = models.BooleanField('Active Client', default = True)

   class Meta:
      verbose_name = 'People'
      verbose_name_plural = 'People'
      ordering = ['Name']

   def __str__(self):
      return "{0} - {1}".format(self.Name, self.Last_Name.capitalize())

class Birthday(models.Model):
   People_Birthday = models.OneToOneField(People, on_delete = models.CASCADE)
   BirthdayCalendar = models.DateField('Birthday', blank = False, null = False)

   class Meta:
      verbose_name = 'Birthday'
      verbose_name_plural = 'Birthdays'
   def __str__(self):
      return str(self.People_Birthday)

You can override the get_queryset method of a model manager.

class BirthdayManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(People_Birthday__State=True) #Not recommended

    def active(self):
        return super().get_queryset().filter(People_Birthday__State=True) #Recommended

This isn't really recommended, since it will also affect the adminsite. (If you override get_queryset())

You can create another method though, and always use that.

This is on a manager, but it's better to put stuff like this on a queryset in my opinion.

class BirthdayQuerySet(models.QuerySet):
    def active(self):
        return self.filter(People_Birthday__State=True)

This way you can append it at all times to your queryset. As opposed to only a manager, which does not allow you to use the method after filtering for example. With a queryset, you can still do Birthday.objects.filter(date__range=your_date_range).active()

With a manager that would error.

To use a queryset on your model add this attribute to your model:

objects = BirthdayQuerySet.as_manager()

To use a modelmanager:

objects = BirthdayManager()

You can use both, but that's out of the scope of this question.


Person is singular. People is plural.

Back to Top