【发布时间】:2017-11-22 17:49:47
【问题描述】:
我有以下型号和形式:
# Model
class Fruit(...):
name = models.CharField(...) # Default name of the fruit
engName = models.CharField(...) # English name
def __str__(self):
return self.name
# Form
class ComboProductForm(forms.ModelForm):
fruit = forms.ModelChoiceField(queryset=Fruit.objects.none())
def __init__(self, *args, **kwargs):
branch = kwargs.pop('branch')
fruits = Fruit.objects.filter(branch=branch) # Branch of the company
self.fields['fruit'].queryset = fruits
公司的每个分公司都有不同的水果,所以我必须在__init__方法中过滤水果。我想要的是根据request.LANGUAGE_CODE修改查询集:
def __init__(self, *args, **kwargs):
branch = kwargs.pop('branch')
language = kwargs.pop('language')
fruits = Fruit.objects.filter(branch=branch) # Branch of the company
if language == 'en':
for fruit in fruits:
fruit.name = fruit.engName
self.fields['fruit'].queryset = fruits
也就是说,如果语言代码是英文,则显示英文水果名称。但是,生成的fruits 的内容似乎没有改变。如何修改查询集?
我也尝试了以下方法:
fruits = list(fruits)
for fruit in fruits:
fruit.name = fruit.engName
但是我必须将fruits 转换回查询集类型。我该怎么做,这会奏效吗?
我也在考虑在模型方法__str__中返回不同的字段:
def __str__(self):
if language_code == 'English': # Hypothetical statement
return self.name
return self.engName
但不知道该怎么做。请帮忙,谢谢。
【问题讨论】:
标签: django-models django-forms django-queryset