Shift 'n Tab
Shift 'n Tab

Reputation: 9443

Add custom fields in a serializer based from instance criteria

I created a Django 1.10 app with Rest-Framework, I have trouble making any custom field that will yield the date range of a date field in M2MField, 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
    }
]

Upvotes: 1

Views: 842

Answers (1)

AnnShress
AnnShress

Reputation: 488

What you want are serializers.

You can override the default result returned from the serializer's to_representation() function. And add min_date and max_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

Upvotes: 4

Related Questions