How to make sure only one BooleanField is true for a single model?

Related searches

I have a django project in which I have a Videos model. On my index template page I only want to show a single video, the one that has isFeatured equal to true. Whenever I change another video's isFeatured property to true, it should make that property false for the former video.

I've checked out other stackoverflow questions about this but all of them are dealing with a foreign key, while my model is simpler and I think there is an easier solution for this.

This is how my model looks like:

class Video(models.Model):
    url = models.URLField(max_length=200)
    isFeatured = models.BooleanField(default=False)

    def __str__(self):
        return self.url

If you really don't want or can't create another model then the only solution for you would be handling this by codes.

The only way you can get around this is that you have to change the rows with a code.

And to get it right, create a function that does this and use it everywhere instead of rewriting the code to avoid mistakes.

video_isfeatured_changer(video_id):
    # Change isFeatured for other featured videos to False.
    featured_videos = Video.objects.filter(isFeatured=True).update(isFeatured=False)

    video = Video.objects.get(pk=video_id)
    video.isFeatured = True
    video.save()

You can also override the save() method for Video model.

Django: Allowing only one booleanfield to be True, Which photo is on the cover of the album should be a property of the album, not the Photo. Instead of using a boolean property in your Photos, use a reference to � The models.NullBooleanField or models.BooleanField does not translate correctly the values 0/1 False / True from version 1.8 of Django. For example, users are shown all as superuser and staff (as if the database were setup to 1 - True) even if the corresponding values in the database are 0 (False).

class Video(models.Model):
    url = models.URLField(max_length=200)
    isFeatured = models.BooleanField(default=False)

    def mark_featured(self):
        self.objects.all().update(isFeatured=False)
        self.isFeatured = True
        return self.save()

    def __str__(self):
        return self.url

Use as

video = Video.objects.get(...)
video.mark_featured()

Boolean Field. How can I make all other records FALSE when a , class Student(models.Model): So, there can be only one who is selected. How can I make all other records FALSE when a single record is made TRUE? Only Replace the <_name> with your models value for _name. How do I determine if *exactly* one boolean is true, without type conversion? Given an arbitrary list of booleans, what is the most elegant way of determining that *exactly* one of them is true? The most obvious hack is type conversion: converting them to `0` for `false` and `1` for `true` and then summing them, and returning `sum == 1`.

The first video with isFeatured = True

class Video(models.Model):
    url = models.URLField(max_length=200)
    isFeatured = models.BooleanField(default=False)

    def __str__(self):
       return self.url

    def homeheader(self):
       return self.filter(isFeatured=True).first()

You can use at the template like:

{{ videos.homeheader }}

Form fields | Django documentation, When you create a Form class, the most important part is defining the fields of the form. By default, each Field class assumes the value is required, so if you pass an empty This is why initial values are only displayed for unbound forms. If you want to include a boolean in your form that can be either True or False (e.g. a � Apply a CHECK constraint to the table that calls a UDF and makes sure its return value is <= 1. The UDF can just count the rows in the table WHERE isDefault = TRUE. This will ensure that there is no more than 1 default row in the table.

Thank you for the help. I managed to solve the problem by overriding the save method:

class Video(models.Model):
    url = models.URLField(max_length=200)
    isFeatured = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        if self.isFeatured == True:
            Video.objects.filter(isFeatured=True).update(isFeatured=False)
        super().save(*args, **kwargs)

    def __str__(self):
        return self.url

I'll wait a bit until I approve this answer, since I'm not very familiar with django so I don't know what problems this may or may not cause.

Model field reference | Django documentation, Grouped options may be combined with ungrouped options within a single list ( such as the If you don't specify primary_key=True for any field in your model, Django will automatically add an Only one primary key is allowed on an object. The default value of BooleanField is None when Field.default isn't defined. If you put quotation marks on a single word in Google, it will defeat the auto-stemming feature and only return that specific word. There you have it – Boolean basics! If there is something you would like to see me post about with regard to Boolean logic and search tactics and strategies – let me know.

Need help with unique_together, from django.db import models class Product(models.Model): title = models. Well boolean field can have only two values: "true" or "false". Now your intended to do. There isn't really one single solution for your problem. -- If it is True - the default - then if the ForeignKey is pointing at a model which matches the current value of settings.AUTH_USER_MODEL (or another swappable model setting) the relationship will be stored in the migration using a reference to the setting, not to the model directly. You only want to override this to be False if you are sure your

We use the logical or operator to set the condition to true if mynumber is either less than 1 or greater than 2. Since we set the variable with a value of 0, this if statement evaluates to true. Remember with the logical or statement, only one condition must evaluate to true for the entire if statement to return true.

I've seen the one-assert-per-method philosophy abused in the past. An old co-worker used a funky inheritance mechanism to make this possible. It led to a lot of sub-classes (one per branch) and lots of tests that did the same set-up/tear-down process only to check the different results.

Comments
  • Perhaps using an extra model with one element: a ForeignKey to the Video that is featured is a better modeling here, since then, by design, it is impossible to have multiple featured videos.