Given two models with a many-to-many relationship between them.
class Collection(models.Model):
title = models.CharField(max_length=200, unique=True, verbose_name="Title")
class Content(models.Model):
author = models.CharField(max_length=200, unique=True, verbose_name="Author")
collection = models.ManyToManyField(Collection, verbose_name="Collection")
public = models.BooleanField(default=True, verbose_name="Public")
How can I filter the Collection
to only list Content
where public == True
?
serializers.py
:
class ContentSerializer(serializers.ModelSerializer):
class Meta:
model = Content
fields = ["author"]
class CollectionSerializer(serializers.ModelSerializer):
content_set = ContentSerializer(many=True, read_only=True)
class Meta:
model = Collection
fields = [
"title",
"content_set",
]
<代码>view.py:
class CollectionViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Collection.objects.all()
serializer_class = CollectionSerializer
permission_classes = [permissions.AllowAny]
def get_queryset(self):
return Collection.objects.filter(content_set__enable=True) # Not working as expected
预期产出:
[
{
"title": "Foo",
"content_set": [
{
"author": "Jane Doe"
}
]
}
]