how to set non-database field on a model in django

Viewed 48

i want to set / update calculated field on a model, with a different value on each object.

for example, i have a User model, and i want to set a name property on each user, where name is not a column on the DB and it can't be edited by the user.

the names can come from get_all_users_names() or from get_name_by_user_id(id).

where should i set it and how should i set it? im new with python so please share some code :) thanks

1 Answers

You have a few options:

  1. Store the full_name on the database but not set by a form or on the admin, you can use a post_save signal to update the field based on the first_name and last_name fields. You will be able to easily filter and do other DB actions on this column, but you might need to hide the field in a few areas so that it isn't editable.

  2. Use a Model method to generate the full name, you can then access this in your views and template - however, you won't be able to do any filtering or other DB actions:

class MyModel(models.Model):
   ...

   @property
   def full_name(self):
       return f'{self.first_name} {self.last_name}'
  1. The best option is to annotate your queryset with a full name that concatenates the first_name and last_name field - you can filter the annotation and call it in your templates and views very easily.
from django.db.models.functions import Concat, Value

User.objects.annotate(
   name=Concat('first_name', V(' '), 'last_name'), 
   output_field=CharField())
)
Related