以下模型允许我在数据库中处理翻译,而无需调整代码来添加语言。
class NameString(models.Model)
en = models.CharField(max_length=55)
de = models.CharField(max_length=55)
在模型中使用的示例称为
项目
:
class Item(models.Model):
name = models.ForeignKey(NameString)
我使用ReadOnlyModelViewSet通过api进行查看。返回以下json:
"results": [
{
"id": 1,
"name": 3,
}
]
我想更换
身份证件
中的值
名称
具有给定语言中实际名称的json字段。这可以通过注释查询集来实现,例如:
name_field = 'name__{}'.format(self.language())
queryset = Item.objects.annotate(name_value=F(name_field))
如果使用带值的序列化程序
name\u值
,我得到以下json:
"results": [
{
"id": 1,
"name_value": 'cucumber',
}
]
我的问题是
:如何编写管理器来处理
项目
ItemList模型中的ManyToMany字段,以便返回指定语言的查询集?
class ItemList(models.Model):
items = models.ManyToManyField(Item)
所以我得到了以下json:
"results": [
{
"id": 1,
"name": "item_list_1",
"items" [
{
"id": 1,
"name_value": "cucumber"
},
{
"id": 2,
"name_value": "apple"
}
],
}
]