How do I make a Boolean field model to accept only 1 true and multiple false values in Django?

Asked

Viewed 26 times

-1

An example of a client’s model address:

class Address(models.Model):

    activate = models.BooleanField(null=False, default=False)

    AddressLine1 = models.CharField(max_length=60, blank=True, null=True)
    AddressLine2 = models.CharField(max_length=60, blank=True, null=True)
    country = models.CharField(max_length=50, null=True, blank=True)
    postalCode = models.CharField(max_length=20, null=True, blank=True)
    stateProvinceRegion = models.CharField(max_length=50, null=True, blank=True)
    city = models.CharField(max_length=50, null=True, blank=True)

As I do to inform the bank that the "Activate" field can have only 1 value of type "true" and several of type "false", that is, I can only have an "active" address (true) and the others need to be "disabled"(false).

The customer needs the freedom to change his active address but maintaining the same rule of only 1 address with active status (true) at a time!

1 answer

0

class Address(models.Model):

    ...

    activate = models.BooleanField(blank=False, null=False, default=False)


    def save(self):
        if self.activate:
            addresses = Address.objects.filter(activate=True)
            for address in addresses:
                address.activate = False
                address.save()
        super().save()

Other examples on how to solve the same problem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.