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 ?
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()
You can define model'sproperty
:
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.