根据实例条件在串行器中添加自定义字段 [英] Add custom fields in a serializer based from instance criteria
问题描述
我创建了一个 Django 1.10
应用程序与 Rest-Framework
,我有麻烦制作任何自定义字段将产生日期字段的日期范围在 M2MField
中,我将用我的代码解释我的问题。
FoodConsumption(models.Model):
'''
动物消耗的物品。
'''
animal = models.ForeignKey(
Animal,related_name ='animal_food_consumptions',on_delete = models.CASCADE)
food = models .ForeignKey(
Food,related_name ='food_consumptions',on_delete = models.CASCADE)
date = models.DateField()
class FoodConsumptionTransaction (models.Model):
herd = models.ForeignKey(
Herd,related_name =food_consumption_transactions,
on_delete = models.CASCADE
)
food_consumptions = models.ManyToManyField(FoodConsumption)
这里是我的序列化程序显示 FoodConsumptionTransaction
数据。
class FoodConsumptionTransactionListSerializer(serializers.ModelSerializer):
class Meta:
model = FoodConsumptionTransaction
fields = ['id','herd','food_consumptions']
创建两个 FoodConsumption
:
from dateutil import parser
fc1 = FoodConsumption.objects.create(
animal = animal_obj_1,
food = food_obj_1,
date = parser.parse(' 2017-04-06')。date()// min date
)
fc2 = FoodConsumption.objects.create(
animal = animal_obj_2,
food = food_obj_2,
date = parser.parse('2017-04-08')。date()
)
fc3 = FoodConsumption.objects.create(
动物= animal_obj_3,
food = food_obj_2,
date = parser.parse('2017-04-10')。date()//最大日期
)
#add to the transaction
fc_trans = FoodConsumptionTransaction.objects.create(
herd = herd_obj_1
)
fc_trans .food_consumptions.add(fc1,fc2,fc3)
现在,通过herd我们获取 FoodTransaction
的数据获得此列表:
[
$但是,如何根据
{
id:1,
herd:1,
food_consumptions:[1,2,3],FoodComsumption的$ p
}
]
food_consumptions
字段创建额外的字段,$ code> food.date (最小和最大)?[
{
id:1,
herd:1,
food_consumptions:[1,2,3],FoodComsumption的$ p
min_date:' 04-6',#获取食物的最小日期
max_date:'2017-04-10',#获取食物的最大日期
}
]
解决方案你想要的是序列化程序。
您可以覆盖从串行器的
to_representation()
函数。并为生成的结果添加min_date
和max_date
字段。
如
class FoodSerializer(serialiers.ModelSerializer):
def to_representation(self,instance):
result = super(FoodSerializer,self).to_representation(instance)
result ['min_date'] = min [each.date for each in instance.m2mfield.all()]
result ['max_date '] = max [each.date for each in example.m2mfield.all()]
return result
I created a
Django 1.10
app withRest-Framework
, I have trouble making any custom field that will yield the date range of a date field inM2MField
, i will explain my problem with my code.class FoodConsumption(models.Model): ''' An item consume by animal. ''' animal = models.ForeignKey( Animal, related_name='animal_food_consumptions', on_delete=models.CASCADE) food = models.ForeignKey( Food, related_name='food_consumptions', on_delete=models.CASCADE) date = models.DateField() class FoodConsumptionTransaction(models.Model): herd = models.ForeignKey( Herd, related_name="food_consumption_transactions", on_delete=models.CASCADE ) food_consumptions = models.ManyToManyField(FoodConsumption)
And here is my serializer to display the
FoodConsumptionTransaction
data.class FoodConsumptionTransactionListSerializer(serializers.ModelSerializer): class Meta: model = FoodConsumptionTransaction fields = ['id', 'herd', 'food_consumptions']
Create a couple of
FoodConsumption
:from dateutil import parser fc1 = FoodConsumption.objects.create( animal=animal_obj_1, food=food_obj_1, date=parser.parse('2017-04-06').date() // min date ) fc2 = FoodConsumption.objects.create( animal=animal_obj_2, food=food_obj_2, date=parser.parse('2017-04-08').date() ) fc3 = FoodConsumption.objects.create( animal=animal_obj_3, food=food_obj_2, date=parser.parse('2017-04-10').date() // max date ) # add to the transaction fc_trans = FoodConsumptionTransaction.objects.create( herd=herd_obj_1 ) fc_trans .food_consumptions.add(fc1, fc2, fc3)
Now when getting data of
FoodTransaction
by herd i get this list:[ { "id": 1, "herd": 1, "food_consumptions": [1, 2, 3], # pks of FoodComsumption } ]
But how can i create extra fields based from
food_consumptions
field ,food.date
(min and max)?[ { "id": 1, "herd": 1, "food_consumptions": [1, 2, 3], # pks of FoodComsumption "min_date": '2017-04-6', # get the min date of food "max_date": '2017-04-10', # get the max date of food } ]
解决方案What you want are serializers.
You can override the default result returned from the serializer's
to_representation()
function. And addmin_date
andmax_date
fields to the result produced.Such as
class FoodSerializer(serialiers.ModelSerializer): def to_representation(self, instance): result = super(FoodSerializer, self).to_representation(instance) result['min_date'] = min[each.date for each in instance.m2mfield.all()] result['max_date'] = max[each.date for each in instance.m2mfield.all()] return result
这篇关于根据实例条件在串行器中添加自定义字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!