Ad

How To Set A Model Boolean Field Based On Conditional Logic Of Other Field Values

- 1 answer

I have a Template model with a 1:many FK with a Post model:

class Template(model.Models):
    #foo

class Post(model.Models):
    template = models.ForeignKey(
        Template, null=True, on_delete=models.SET_NULL)

I want to create an 'automatic' boolean field that flags if there is one or more posts using the template (if True I will lock the template for editing).

What's the best way to do this? Is it via a @property decorator on the Template model??:

@property
def can_edit(self):
    if self.object.post_set.all() >= 1:
        self._can_edit = True
        return self._can_edit
    else:
        self._can_edit = False
        return self._can_edit

Then I would call this via {{ template.can_edit }} to display the flag status and {% if template.can_edit() %} to run conditional logic, but this does not work.

Ad

Answer

You can try:

@property
def can_edit(self):
    return self.post_set.count() == 0

And in your template:

{% if template.can_edit %}
Ad
source: stackoverflow.com
Ad