One way I can think of is to add a property 
<https://docs.python.org/3/library/functions.html#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 
<https://docs.djangoproject.com/en/2.2/ref/models/querysets/#django.db.models.query.QuerySet.annotate>.
 
With annotations, you can do aggregations, just like with any other model 
field.


On Monday, 21 October 2019 20:05:04 UTC+2, Eileen Bauer wrote:
>
> 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
>
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/cd4aed5d-223b-4c9a-9678-aa0fd5b9464f%40googlegroups.com.

Reply via email to