'django rest framework serializer add an auto generated field when getting data
I want to automatically generate a field when data comes out of the database. Here is an example serializer I have:
class SaleSerializer(serializers.ModelSerializer):
class Meta:
model = Sale
fields = '__all__'
I want this serializer to have two extra fields that dynamically generate one called username which has a string username of the user object and the other shop name that has the name of the shop object.
Here is the model of sale that the serializer uses:
class Sale(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
shop = models.ForeignKey(Shop, on_delete=models.DO_NOTHING)
reciept = models.TextField()
date_time = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"reciept number {self.pk}"
Solution 1:[1]
Try this (I have presumed that your Shop model has a field called name since you din't provide the class):
class SaleSerializer(serializers.ModelSerializer):
username = serializers.SerializerMethodField()
shop_name = serializers.SerializerMethodField()
def get_username(self, obj):
return obj.user.username
def get_shop_name(self, obj):
return obj.shop.name
class Meta:
model = Sale
fields = ['user', 'shop', 'reciept', 'date_time', 'username', 'shop_name']
Solution 2:[2]
Assuming the name field stores the name of shop & user in their respective models. There is another you can achieve this using source argument in a serializer field apart from mentioned by RedWheelbarrow.
class SaleSerializer(serializers.ModelSerializer):
username = serializers.Charfield(source='user.name')
shopname = serializers.Charfield(source='shop.name')
class Meta:
model = Sale
fields = '__all__'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RedWheelbarrow |
| Solution 2 | Sukhpreet Singh |
