Reputation: 1623
Rather than a long explication, some code :
My main serializer OrderSerializer
and the nested serializer OffersSerializer
:
class OffersSerializer(serializers.Serializer):
id = serializers.IntegerField(min_value=0)
quantity = serializers.IntegerField(min_value=0)
class OrderSerializer(serializers.Serializer):
offers = OffersSerializer(many=True, required=True)
With that I can POST data like this :
{
"offers": []
}
This is valid for DRF, but I would like to check there is at least one offer, so for example:
{
"offers": [{"id": 1, "quantity": 200}]
}
How can I ensure that there is at least one offer ?
Thank you
Upvotes: 5
Views: 1557
Reputation: 7717
class OrderSerializer(serializers.Serializer):
def validate_offers(self, attrs):
if len(attrs) == 0:
raise serializers.ValidationError('at least one offer required')
return attrs
Upvotes: 5
Reputation: 581
Work with the Manger oder your serzializer-model, e.g.:
if (mySerializerModel.objects.all()[0] != None):
# some code
pass
There are other possibilities to check this. I think there is even a count()
method for your managers.:
if (mySerializerModel.objects.all().count() > 0):
# some code
pass
Further there are mySerializerModel.objects.get(<id>)
if you know the id. There might be other possibilites to check that. Just have a look at the django queryset documentation.
Upvotes: 0