aswin s sekhar
aswin s sekhar

Reputation: 11

How to switch a boolean field when there is a change in another field in django?

I'm trying to switch a boolean field (tagged) when there is a change in the ManyToMany field(tag). How can i do that?

class Tagger(models.Model):
    tagged = models.BooleanField(default = False)
    appName =  models.ForeignKey(AppName,on_delete=models.CASCADE, null=True, blank=True)
    tag = models.ManyToManyField(Tag,blank=True)

I expect the 'tagged' field to switch to True when there is an input in 'tag' and vice versa.

Upvotes: 0

Views: 846

Answers (1)

user8060120
user8060120

Reputation:

it looks like the simple way is use property

class Tagger(models.Model):
    appName =  models.ForeignKey(AppName,on_delete=models.CASCADE, null=True, blank=True)
    tag = models.ManyToManyField(Tag, blank=True)

    @property
    def tagged(self):
        return bool(self.tag.all())

to display the field in the admin dashboard just add it to the list_display, for example:

class TaggerAdmin(admin.ModelAdmin):
    list_display = (..., 'tagged')

Upvotes: 2

Related Questions