根据实例条件在序列化程序中添加自定义字段

时间:2017-04-06 00:41:01

标签: django django-rest-framework

我使用Django 1.10创建了一个Rest-Framework应用,我无法制作任何自定义字段,以便在M2MField中生成日期字段的日期范围,我将解释我的问题代码。

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)

这是我的序列化程序,用于显示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=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)

现在,当我从牧群获取FoodTransaction的数据时,我会得到这个列表:

[
   {
       "id": 1,
       "herd": 1,
       "food_consumptions": [1, 2, 3], # pks of FoodComsumption
   }
]

但是如何根据food_consumptions字段food.date (最小和最大)创建额外字段?

[
    {
        "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
    }
]

1 个答案:

答案 0 :(得分:4)

你想要的是serializers

您可以覆盖序列化程序的to_representation()函数返回的默认结果。并在生成的结果中添加min_datemax_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 instance.m2mfield.all()] 
        return result