我正在使用django-modeltranslation在DRF中翻译mo模型
所以我做了所有说django-modeltranslation的文档,并且它适用于模型字段
但是我无法获得Choicefield的翻译价值
from django.utils.translation import ugettext_lazy as _
class Product(models.Model):
PRODUCT_TYPES = (
('food', _('food')),
('wear', _('wear'))
)
name = models.CharField(verbose_name='Name', max_length=512, blank=True)
product_type = models.CharField('Type', choices=PRODUCT_TYPES, blank=True, null=True, max_length=16, default='food')
product_name
之类的字段由django-modeltranslation翻译并可以正常工作
但是我总是在food
中得到product_type
我运行makemessages和compilemessages
msgid "food"
msgstr "еда"
msgid "wear"
msgstr "одежда"
调用get_product_type_display无效
class ProductSerializer(serializers.ModelSerializer):
date = serializers.DateTimeField(read_only=True, format='%d.%m.%Y %H:%M')
product_type = serializers.SerializerMethodField()
class Meta:
model = Product
fields = ('phone_number', 'name', 'total_bonus', 'card_number', 'id', 'count', 'date', 'product_type',
'category')
def get_product_type(self, obj):
return obj.get_product_type_display()
答案 0 :(得分:0)
我找到了解决此问题的方法。需要使用:package com.company;
import java.util.HashMap;
import java.util.Map;
public class Repository {
private Map<Long, Product> product_repository = new HashMap<Long, Product>();
// TO DO: Implement while loops so program doesn't exit at the first error
public void save_product(Long key, Product newProductMap){
try{
if (product_repository.containsValue(newProductMap)) {
System.out.println("This product is already in the system." +
"\nFor safety reasons, we cannot add the same product twice.");
}
else {
product_repository.put(key, newProductMap);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
public void find_product(Long key){
try {
if (product_repository.containsKey(key)) {
System.out.println(product_repository.get(key));
}
else {
System.out.println("No matches were found for product id: " + key);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
// Overload
public void find_product(String name) {
try {
if (product_repository.containsValue(name)) {
System.out.println(product_repository.get(name));
product_repository.keySet().iterator().forEachRemaining(System.out::println);
}
else {
System.out.println("No matches were found for product name: " + name);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
}
return _(obj.product_type)
答案 1 :(得分:0)
使用get_FIELDNAME_display()对象方法的序列化器:
attrs