简体   繁体   English

django 模型翻译不适用于此类查询集

[英]django modeltranslation doesn't work with such queryset

I'm new to programming.我是编程新手。

In my blog I want to show a list of categories.在我的博客中,我想显示一个类别列表。 If I create a queryset like this:如果我创建这样的查询集:

Category.objects.all()

my django-modeltranslation works perfectly.我的 django-modeltranslation 效果很好。

But I want to get categories of only published posts.但我想获得仅发布帖子的类别。 Then my queryset is:然后我的查询集是:

Post.objects.values('category__name').filter(is_published=True)

However, django-modeltranslation doesn't work.但是,django-modeltranslation 不起作用。 I get values from 'name' field instead 'name_en' or 'name_ru' fields.我从“name”字段而不是“name_en”或“name_ru”字段中获取值。

What is wrong?怎么了?

Here's my models.py:这是我的models.py:

class Category(models.Model):
    name = models.TextField(max_length=100)
    url = models.SlugField(max_length=160, unique=True)


class Post(models.Model):
    title = models.TextField('title', max_length=150)
    category = models.ManyToManyField(Category, related_name='posts', blank=True) 

I think you better query in reverse: with .values(…) you select a specific database column, so this will omit the model logic.我认为你最好反向查询:使用.values(…)你 select 一个特定的数据库列,所以这将省略 model 逻辑。

You can retrieve the categories with:您可以使用以下方法检索类别:

Category.objects.filter(posts__is_published=True).distinct()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM