1

我有模型Product

class Product(TranslatableModel):
    name = models.CharField(max_length=255, unique=True)

    translations = TranslatedFields(
        description=models.TextField(),
    )

在产品详细信息的管理中,我有带有语言的标签。例如标签 EN、CZ,每个都包括disctiption. 所以 PUT 请求看起来像:

{
    'product': '1',
    'id': 1,
    'name': 'Name', 
    'translations': {
        'cz': {'desctiption': 'Description cz'},
        'en': {'desctiption': 'Description en'}
    }
}

我在django-hvad TranslationsMixin中创立,它允许我完成这个请求。

在序列化程序中我有:

class ProductTranslationSerializer(serializers.ModelSerializer):
    class Meta:
        exclude = ['description']


class ProductSerializer(TranslationsMixin, serializers.ModelSerializer):
    class Meta:
        model = Product
        translations_serializer = ProductTranslationSerializer
        fields = (
            'name', 
            'description',
        )

问题是这个请求的 ModelViewSet 看起来如何?我可以选择像'language_code = en'这样的语言,过滤那个查询并得到类似的东西:

[
    {
        id: 1
        name: "name"
        descritpion: "descritpion"
    },
    ....
]

谢谢!

4

2 回答 2

1

我最有可能实现的方法是:

模型.py

class Product(TranslatableModel):
    category = models.ForeignKey('product.ProductCategory',
                                 related_name='product_category',
                                 null=True,
                                 on_delete=models.SET_NULL,
                                 verbose_name=u'category')
    cover = models.ImageField(upload_to=product_cover,
                              null=True,
                              verbose_name=u'cover')
    translations = TranslatedFields(
        title=models.CharField(max_length=100,
                               null=True,
                               verbose_name=u'title'),
        summary=models.TextField(null=True,
                                 verbose_name=u'summary'),
        model=models.CharField(max_length=255,
                               null=True,
                               blank=True,
                               verbose_name=u'model'),
        price=models.DecimalField(default=0.00,
                                  max_digits=10,
                                  decimal_places=2,
                                  blank=True,
                                  validators=[MinValueValidator(0)],
                                  verbose_name=u'price'),
        content=models.TextField(verbose_name=u'content'),
        publish_time=models.DateTimeField(default=timezone.now,
                                          verbose_name=u'发布publish_time')

    )
    view_times = models.IntegerField(default=0,
                                     verbose_name=u'view_times ')

视图.py

class ProductViewSet(ModelViewSet):
    serializer_class = ProductListSerializer

    def get_queryset(self):
        if 'language_code' in self.request.GET:
            language_code = self.request.GET.get('language_code')
            queryset = Product.objects.language(language_code).order_by('-id')
        else:
            queryset = Product.objects.language().order_by('-id')
        return queryset

序列化程序.py

class ProductCategorySerializer(TranslatableModelSerializer):
    class Meta:
        model = ProductCategory
        fields = '__all__'



class ProductListSerializer(TranslatableModelSerializer):
    category = ProductCategorySerializer(read_only=True)

    class Meta:
        model = Product
        exclude = ['is_abandon', 'content', ]

网址.py

   from rest_framework import routers
   router = routers.DefaultRouter()
   router.register(r'product', ProductViewSet, base_name='api-product')
   ...

结果: http: //192.168.1.108/api/product/ ?language_code=zh-hans你得到:

{
    "count": 1,
    "page_num": 1,
    "page_no": 1,
    "next": "",
    "previous": "",
    "results": [
        {
            "id": 2,
            "category": {
                "id": 2,
                "create_time": "2017-08-10 16:49:41",
                "update_time": "2017-08-18 08:56:02",
                "name": "测试",
                "language_code": "zh-hans"
            },
            "create_time": "2017-08-18 08:53:46",
            "update_time": "2017-08-18 08:56:28",
            "cover": "http://192.168.1.108/media/product/20170818-085346-518_59.jpg",
            "view_times": 0,
            "title": "标题",
            "summary": "简介",
            "model": null,
            "price": "90.00",
            "publish_time": "2017-08-18 08:53:00",
            "language_code": "zh-hans"
        }
    ]
}

http://192.168.1.108/api/product/?language_code=en你得到:

{
    "count": 1,
    "page_num": 1,
    "page_no": 1,
    "next": "",
    "previous": "",
    "results": [
        {
            "id": 2,
            "category": {
                "id": 2,
                "create_time": "2017-08-10 16:49:41",
                "update_time": "2017-08-18 08:56:02",
                "name": "测试",
                "language_code": "zh-hans"
            },
            "create_time": "2017-08-18 08:53:46",
            "update_time": "2017-08-18 09:00:23",
            "cover": "http://192.168.1.108/media/product/20170818-085346-518_59.jpg",
            "view_times": 0,
            "title": "title",
            "summary": "summary",
            "model": "model",
            "price": "91.00",
            "publish_time": "2017-08-18 08:56:04",
            "language_code": "en"
        }
    ]
}

这样 fk 不会改变语言,如果你想 fk 也改变语言,使用:urls.py

urlpatterns += i18n_patterns(
    '''
    url(r'^api/', include(router.urls)),
    prefix_default_language=False,
)

改变语言

 http://192.168.1.108/zh-hans/api/product/

 http://192.168.1.108/en/api/product/

你会得到:

{
    "count": 1,
    "page_num": 1,
    "page_no": 1,
    "next": "",
    "previous": "",
    "results": [
        {
            "id": 2,
            "category": {
                "id": 2,
                "create_time": "2017-08-10 16:49:41",
                "update_time": "2017-08-18 08:56:02",
                "name": "test",
                "language_code": "en"
            },
            "create_time": "2017-08-18 08:53:46",
            "update_time": "2017-08-18 09:00:23",
            "cover": "http://192.168.1.108/media/product/20170818-085346-518_59.jpg",
            "view_times": 0,
            "title": "title",
            "summary": "summary",
            "model": "model",
            "price": "91.00",
            "publish_time": "2017-08-18 08:56:04",
            "language_code": "en"
        }
    ]
}
于 2017-08-18T00:39:32.843 回答
0

来自 django-hvad github repo @spectras 所有者的回答:

如果我理解得很好,您想为集合端点和项目端点使用不同的序列化形式。也就是说,GET-1、PUT、POST 将使用翻译 mixin,而 GET-many 则不会。为此,您需要两个有两个不同的序列化程序:

  1. 你创建的那个
  2. 另一个是,例如, class ProductItemSerializer(TranslatableModelSerializer):...

另一个,例如,类 ProductItemSerializer(TranslatableModelSerializer): ... 鉴于此,您可以向 ModelViewSet 添加一个根据请求类型动态选择序列化程序类的方法:

class SomeModelViewSet(ModelViewSet):
    # serializer_class = not needed, we use the method instead
    def get_serializer_class(self):
        if self.action == 'list':
            return ProductItemSerializer
        return ProductSerializer

另一种可能更容易在 Javascript 端使用的方法是为 Product 模型创建 2 个视图集,一个可读写的视图集是翻译感知的(使用 ProductSerializer),一个只读的不感知翻译,使用 (ProductItemSerializer) .

同样,我通常只有不支持翻译的序列化程序,并添加一个支持翻译的 /api/product/details/ 端点。这样,在客户端进入编辑/详细模式时,我只需要处理 dict 对象的复杂性。

于 2017-08-18T08:31:36.100 回答