如何将多个Django模型一起收集到一个列表中?

时间:2022-02-13 21:52:20

I have a fairly straightforward blog in Django, with separate models for Article and Link. I want to have a loop in my template that lists them both in date order, which means something like this:

我在Django中有一个相当简单的博客,有文章和链接的单独模型。我想在我的模板中有一个循环,它按日期顺序列出它们,这意味着这样的事情:

def listview(request):
    return render_to_response('index.dtmpl', {
        'articles' : ArticlesAndLinks.objects.order_by('post_date')[:10]
    }, context_instance = RequestContext(request)

I'm not sure how to do this. Do I have to grab Articles.objects.order_by('post_date') and Links.objects.order_by('post_date') separately, merge them, and reorder? Or is there a nicer Django-ish/Pythonic way to accomplish this?

我不知道该怎么做。我是否必须单独抓取Articles.objects.order_by('post_date')和Links.objects.order_by('post_date'),合并它们并重新排序?或者是否有更好的Django-ish / Pythonic方法来实现这一目标?

If it helps, Posts and Links are both subclasses of an abstract class, Post, but as it's an abstract class it appears I can't run collections on it.

如果它有帮助,帖子和链接都是一个抽象类Post的子类,但由于它是一个抽象类,它似乎无法在其上运行集合。

3 个解决方案

#1


1  

Turns out the solution is to turn the abstract class into a real one, and then I can collect over that.

事实证明解决方案是将抽象类转换为真实类,然后我可以收集它。

#2


0  

Well, the obvious answer would have been to make Post a concrete class. Else you'll probably have to squeeze the ORM and resort to handcoded SQL or manually merge/order your two querysets. Given the small size of the dataset, I'd go for this last solution.

嗯,显而易见的答案是将Post作为一个具体的类。否则,您可能需要挤压ORM并使用手动编码的SQL或手动合并/订购两个查询集。鉴于数据集的小尺寸,我会选择最后一个解决方案。

#3


0  

Refactoring could be the better solution, but here is another one that could do the job:

重构可能是更好的解决方案,但这是另一个可以完成工作的解决方案:

Create a custom Manager:

创建自定义管理器:

class PostManager(models.Manager):
    def mixed(self, first):
        all_dates = []
        articles_dates = Articles.objects.extra(select={'type':'"article"'}).values('id', 'post_date', 'type').order_by('-post_date')[:first]
        links_dates = Links.objects.extra(select={'type':'"link"'}).values('id', 'post_date', 'type').order_by('-post_date')[:first]
        all_dates.extend(articles_dates)
        all_dates.extend(links_dates)
        # Sort the mixed list by post_date, reversed
        all_dates.sort(key=lambda item: item['post_date'], reverse=True)
        # Cut first 'first' items in mixed list
        all_dates = all_dates[:first]
        mixed_objects = []
        mixed_objects.extend(Articles.objects.filter(id__in=[item['id'] for item in all_dates if item['type'] = 'article']))
        mixed_objects.extend(Links.objects.filter(id__in=[item['id'] for item in all_dates if item['type'] = 'link']))
        # Sort again the result list
        mixed_objects.sort(key=lambda post: post.post_date, reverse=True)
        return mixed_objects

And use it in your abstract model:

并在您的抽象模型中使用它:

class Post(models.Model):

    class Meta:
        abstract = True

    objects = PostManager()

Then the call for your mixed objects will be:

然后,对混合对象的调用将是:

Article.objects.mixed(10)

#1


1  

Turns out the solution is to turn the abstract class into a real one, and then I can collect over that.

事实证明解决方案是将抽象类转换为真实类,然后我可以收集它。

#2


0  

Well, the obvious answer would have been to make Post a concrete class. Else you'll probably have to squeeze the ORM and resort to handcoded SQL or manually merge/order your two querysets. Given the small size of the dataset, I'd go for this last solution.

嗯,显而易见的答案是将Post作为一个具体的类。否则,您可能需要挤压ORM并使用手动编码的SQL或手动合并/订购两个查询集。鉴于数据集的小尺寸,我会选择最后一个解决方案。

#3


0  

Refactoring could be the better solution, but here is another one that could do the job:

重构可能是更好的解决方案,但这是另一个可以完成工作的解决方案:

Create a custom Manager:

创建自定义管理器:

class PostManager(models.Manager):
    def mixed(self, first):
        all_dates = []
        articles_dates = Articles.objects.extra(select={'type':'"article"'}).values('id', 'post_date', 'type').order_by('-post_date')[:first]
        links_dates = Links.objects.extra(select={'type':'"link"'}).values('id', 'post_date', 'type').order_by('-post_date')[:first]
        all_dates.extend(articles_dates)
        all_dates.extend(links_dates)
        # Sort the mixed list by post_date, reversed
        all_dates.sort(key=lambda item: item['post_date'], reverse=True)
        # Cut first 'first' items in mixed list
        all_dates = all_dates[:first]
        mixed_objects = []
        mixed_objects.extend(Articles.objects.filter(id__in=[item['id'] for item in all_dates if item['type'] = 'article']))
        mixed_objects.extend(Links.objects.filter(id__in=[item['id'] for item in all_dates if item['type'] = 'link']))
        # Sort again the result list
        mixed_objects.sort(key=lambda post: post.post_date, reverse=True)
        return mixed_objects

And use it in your abstract model:

并在您的抽象模型中使用它:

class Post(models.Model):

    class Meta:
        abstract = True

    objects = PostManager()

Then the call for your mixed objects will be:

然后,对混合对象的调用将是:

Article.objects.mixed(10)