问题
I have a situation in which one table is related to another via a foreign key as follows:
models.py
class Container(models.Model):
size = models.CharField(max_length=20)
shape = models.CharField(max_length=20)
class Item(models.Model):
container = models.ForeignKey(Container, related_name='items')
name = models.CharField(max_length=20)
color = models.CharField(max_length=20)
serializers.py
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
class ContainerSerializer(serializers.ModelSerializer):
items = ItemSerializer(many=True)
class Meta:
model = Container
fields = ('size', 'shape', 'items')
This works fine, but my problem is that all the items in the container get serialized. I only want items with color='green' to be serialized.
回答1:
class ContainerSerializer(serializers.ModelSerializer):
items = serializers.SerializerMethodField()
def get_items(self, obj):
query = Item.objects.filter(item_set__color='green')
serializer = ItemSerializer(query, many=True)
return serializer.data
class Meta:
model = Container
fields = ('size', 'shape', 'items')
回答2:
Instead of changing how serializer works, a simplier way, its just filter you Container with green color items and them try to serialize it
You can do something like this:
container_objects = Container.objects.filter(id='your_container_id',item_set__color='green')
serialized_containers = YourContainerSerializer(data=container_objects)
来源:https://stackoverflow.com/questions/25293764/django-rest-framework-query-limit-on-nested-serializer