简化这个Django查询

2024-09-26 22:49:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Post对象,可以联系“Articles”或“Organization”的PostTypes。Posts有一个名为approved的字段,一个名为published的字段,还有一个记录Post所有以前版本的历史记录。我想得到最新的批准和发布的职位。你知道吗

class Post(Published, models.Model):
    headline = models.CharField(max_length=255)
    posttype = models.ForeignKey(PostType)
    organization = models.ManyToManyField('self', null=True,blank=True)
    history = HistoricalRecords() # django-simple-history   
    status = models.IntegerField(
        choices=settings.STATUS_CHOICES,
        default=settings.DRAFT_STATUS, # or can be settings.PUBLISHED_STATUS
        )

class PostType(models.Model):
    slug = models.CharField(max_length=32)
    name = models.CharField(max_length=15)

这是一个图示:

sdf

以下是我获得最新批准和发布的帖子的复杂方法。你知道吗

  def get_context_data(self, **kwargs):
    context = super(ArticleCreate, self).get_context_data(**kwargs)

    # Get me all the posttypes except for articles
    exclude_articles = PostType.objects.exclude(slug__icontains="article")

    # get me approved organizations (i.e. not articles) that are approved
    orgs = Post.objects.filter(approved = True).filter(posttype__in=exclude_articles)
    result = []

    # for each of the organization, get me the latest published history
    for org in orgs:
        result.append(org.history.filter(status=settings.PUBLISHED_STATUS).order_by('-modified_date')[0].history_object)

    context['form'].fields['organization'].queryset = result
    return context

上面的方法返回一个列表而不是queryset(这是另一个问题)。我们能简化这个并得到一个查询集吗?你知道吗


Tags: selfgetsettingsmodelsstatuscontextpostlength
1条回答
网友
1楼 · 发布于 2024-09-26 22:49:19

现在,我还没有尝试过这种重构,所以把它当作一个指针来使用吧!你知道吗

首先,您不需要链接.filter()调用。您可以在一个过滤器调用中“just”使用CSV样式,然后使用Q对象,您就可以在过滤器中执行否定查询。你知道吗

然后我们可以继续使用关系,现在我还没有使用Django简单历史,但我猜它适用于正常的FK遍历。你知道吗

因此,这意味着您可以通过一个普通的history__status访问器访问历史状态,最后,使用.values()方法将允许您直接从DB获取一个只有1个或多个值的列表,从而避免执行res.append(org[0].something)。你知道吗

所以,正如我所说,我还没有尝试过这个代码,但它应该会给你一个正确方向的指针。你知道吗

def get_context_data(self, **kwargs):
    context = super(ArticleCreate, self).get_context_data(**kwargs)

    result = Post.objects.filter(approved = True, ~Q(posttype__slug_icontains="article"), \
                                history__status=settings.PUBLISHED_STATUS) \
                                .order_by('-modified_date').values('history_object')

    context['form'].fields['organization'].queryset = result
    return context

现在这毫无意义,而且很难阅读,所以我建议您将其移动到Post的模型管理器。你知道吗

class PostManager(models.ModelManager):

    def approved_and_published_posts(self):
        return self.get_queryset().filter(approved = True, ~Q(posttype__slug_icontains="article"), \
        history__status=settings.PUBLISHED_STATUS) \
        .order_by('-modified_date').values('history_object')


class Post(models.Model):
    objects = PostManager()

在你看来,你可以这样做:

orgs = Post.objects.approved_and_published_posts()

希望这对你有所帮助,至少能为你指明正确的方向!你知道吗

相关问题 更多 >

    热门问题