【问题标题】:Add custom fields in a serializer based from instance criteria根据实例条件在序列化程序中添加自定义字段
【发布时间】:2017-04-06 00:41:01
【问题描述】:

我使用Rest-Framework 创建了一个Django 1.10 应用程序,我无法创建任何自定义字段来生成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
    }
]

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    你想要的是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
    

    【讨论】:

    • 您好!感谢您的回复,每个循环的语法无效
    • 那是一些简单的逻辑,您可以自己制作以获取minmax 的日期。
    • 我觉得这个对我很有帮助。谢谢你的好主意,我确实在这里学到了一些有用的东西
    • 我不使用min/max [each.date for each in instance.m2mfield.all()],而是将其替换为instance.m2mfield.earliest('date').date 用于最小值,instance.m2mfield.latest('date').date 用于最大值
    • 不错的解决方法,感谢您提供信息。我一直在 django 中忘记这些实用程序。
    猜你喜欢
    • 1970-01-01
    • 2017-08-16
    • 2017-12-09
    • 2014-02-28
    • 2015-04-15
    • 1970-01-01
    • 2015-01-27
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多