how to set up a calculated field in Django?

188 views
Skip to first unread message

Eileen Bauer

unread,
Oct 21, 2019, 2:05:04 PM10/21/19
to Django users
Hi,
i have the following items in my model:
    mother_alive = models.IntegerField(choices=YES_NO_CHOICES, blank=True, null=True, default=1)
    father_alive = models.IntegerField(choices=YES_NO_CHOICES, blank=True, null=True, default=1)

and I'd like to set up a generated field for them so I'd be able to detect whether the child is an orphan or not. In MySQL i believe it'd look like this:
    orphan varchar(101) GENERATED ALWAYS AS (mother_alive+father_alive) VIRTUAL,

I don't know how to change my model to do that...

Any help?

-Eileen

nm

unread,
Oct 22, 2019, 9:34:00 AM10/22/19
to Django users
One way I can think of is to add a property to your model. I believe something like this should work:

```
## in your model class:

    mother_alive = models.IntegerField(choices=YES_NO_CHOICES, blank=True, null=True, default=1)
    father_alive = models.IntegerField(choices=YES_NO_CHOICES, blank=True, null=True, default=1)
   
    @property
    def is_orphan(self):
        return self.mother_alive == 0 and self.father_alive == 0  # not sure what the "no" value is, you have to set it appropriately
```
You'll then be able to access it as an attribute of the model:
```
Child.objects.get(id=1).is_orphan
# True or False
```

This value will not be stored in the database, though, and you won't be able to filter children by the `is_orphan` column, because there'll be no such column.

Another approach would be to use annotations. With annotations, you can do aggregations, just like with any other model field.

wd

unread,
Oct 22, 2019, 11:52:05 PM10/22/19
to django...@googlegroups.com
hi,

Besides the solution provided by @nm,  maybe you can do it by using database trigger ...

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/32b1c56f-f52d-4b63-bd93-db25cc1e89a6%40googlegroups.com.

Tyler Lynch

unread,
Oct 23, 2019, 12:03:03 PM10/23/19
to Django users
If you're using the newest postgres 12, you could also use their new generated column feature (https://www.postgresql.org/docs/current/ddl-generated-columns.html). You can implement that in Django by editing the SQL in the migration setting up your table. Though I do look forward to this feature being integrated more directly into Django as a postgres-specific option, prly won't be too long until it's incorporated. 
Reply all
Reply to author
Forward
0 new messages