2017-04-06 40 views
1

我创建了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:由牛群得到的FoodTransaction数据时

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) 

现在我得到这个名单:

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

回答

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 
+0

您好!感谢您的回应,每个循环都得到了无效的语法 –

+0

这是一些简单的逻辑,您可以自己创建日期的'min'和'max'。 – AnnShress

+0

我觉得这个帮了我很多..感谢一个好主意,我在这里学到了一些有用的东西 –

相关问题