我的模型结构类似于以下模型:
商店->一些商店字段
图书->一些图书字段,可存储FK
BookProperty ->名称,值,图书的FK(一对多关系),要存储的FK
book属性可以存储该书的任何信息,例如。商店添加了no_of_pages,发布者等。
我需要创建一个API端点,在这里我可以获取商店的所有BookProperty。 我使用了网址:
/stores/:store_id/bookproperty
将fields = [publisher, no_of_pages]
与ModelSerializer一起用于BookProperty
将通用视图集与ListModelMixin一起使用。
端点如下所示:
{
"count": 4,
"next": null,
"previous": null,
"results": [
{
"name": "publisher",
"value": "somePublisher"
},
{
"name": "pages",
"value": "1000"
},
{
"name": "publisher",
"value": "someOtherPublisher"
},
{
"name": "publisher",
"value": "somePublisher"
}
]
}
此问题是多个对象可以具有相同的名称和值对。我需要这样的信息,即所有对象都是唯一的并且像这样分组:
{
{"name":"publisher", "value":["somePublisher", "someOtherPublisher"]},
{"name":"pages", "value":["1000"]},
}
我正在尝试覆盖get_queryset(self)
,但是它不起作用。
任何帮助,将不胜感激。预先感谢!
编辑:
models.py
class BookProperty(models.Model):
books = models.ForeignKey(
Books,
on_delete=models.CASCADE,
)
name = models.CharField(max_length=100)
value = models.CharField(max_length=100)
store = models.ForeignKey(
"Store",
on_delete=models.CASCADE,
)
serializers.py
class BookPropertySerializer(serializers.ModelSerializer):
class Meta:
model = models.BookProperty
fields = ["name", "value"]
views.py
class BookPropertyViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = serializers.BookPropertySerializer
我认为与其替代get_queryset(self)
,不如尝试更改def list(self, request, *args, **kwargs)
:
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
tag_dictionary = defaultdict()
things = list(queryset)
for key, group in itertools.groupby(things, lambda x: x.name):
for thing in group:
if key not in tag_dictionary.keys():
tag_dictionary[key] = [thing.value]
else:
tag_dictionary[key].append(thing.value)
for key in tag_dictionary.keys():
tag_dictionary[key] = list(set(tag_dictionary[key]))
return Response(json.dumps(tag_dictionary))
以上解决方案有效,但可能不是最佳解决方案。