-2

I want to add variable in Django model and I don't want to save it to database at the same time I want to return this variable to user when calling the endpoint.

this is what i found in the web, but the problem is the variable is not rerun to user

class User (models.Model):
   f_name = models.CharField(max_length=255)
   l_name = models.CharField(max_length=300)
   full_name = ''

How to rerun the full_name to user when he call the api ?

prg.dev
  • 141
  • 1
  • 3
  • 16
  • Does this answer your question? [How to add a calculated field to a Django model](https://stackoverflow.com/questions/17682567/how-to-add-a-calculated-field-to-a-django-model) – Harun Yilmaz Feb 14 '20 at 13:05
  • no, I need to return the full_name to API – prg.dev Feb 14 '20 at 13:11

2 Answers2

1

You can define model's property:

class User (models.Model):
   f_name = models.CharField(max_length=255)
   l_name = models.CharField(max_length=300)

   @property
   def full_name(self):
       return self.f_name + self.l_name

now you use full_name same way as normal attribute user.full_name.

neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
  • how to rerun to user when i call the API ? – prg.dev Feb 14 '20 at 13:06
  • @prg.dev what exactly did you try? Do you get any error? – neverwalkaloner Feb 14 '20 at 13:08
  • where you use the full_name it depend if you use user at template side write {{ user.full_name }} it will return the full name of login user or you use user in view then write request.user.full_name whenever use django default user with extend if you not use django default user write manual – l.b.vasoya Feb 14 '20 at 13:10
  • no error. when user go to ``` http://localhost:8000/api/userinfo ``` I need to return f_name, l_name, full_name... in the API response it give me only the f_name and l_name – prg.dev Feb 14 '20 at 13:14
  • @prg.dev I think you need to add `full_name` to serializer's fields list. – neverwalkaloner Feb 14 '20 at 13:15
  • is there way to change the full_name from viewset ? – prg.dev Feb 14 '20 at 13:20
1

If this is using Django Rest Framework, I don't know how your code is set up, but you'll need to extend your serializer:

add a new field to the serializer: full_name = serializers.SerializerMethodField()

add a method to the serializer:

def get_full_name(self, obj):
    return "{} {}".format(obj.first_name, obj.last_name)

NOTE: there are LOTS of different ways of joining those strings together, using @property in your model, fstrings, etc - up to you to choose the most appropriate for your needs (without seeing the rest of your code()

RHSmith159
  • 1,823
  • 9
  • 16