alias51
alias51

Reputation: 8608

How to set a model boolean field based on conditional logic of other field values

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.

Upvotes: 1

Views: 562

Answers (1)

Ivan
Ivan

Reputation: 2675

You can try:

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

And in your template:

{% if template.can_edit %}

Upvotes: 1

Related Questions