开发者

Django 2 models 1 "queryset"

开发者 https://www.devze.com 2023-02-11 23:08 出处:网络
I have a news model and a media model. I\'d like to show all the objects on the news page ordered by date.

I have a news model and a media model.

I'd like to show all the objects on the news page ordered by date. They both have date fields and are ordered by ["-date"].

is there a way to do this in the template or should I create a new list and sort the objects in the view?

Thanks in advance.

Ignacio I've read th开发者_Go百科at a few times over the years. How does it relate to my question? [ Ignacio deleted his comment]


I've used something like this:

objects = list(queryset1)+list(queryset2)
objects = sorted(objects, key=lambda x: x.date, reverse=True)

Now for the models I have defined a new method:

def gettype(self):
        return self._meta.verbose_name

which basically gives you the name of the model. Now, in the template you can differentiate between the objects like this:

{% for object in objects %}
    {% if object.gettype == "mediaitem" %}
        {{ object.some_attribute }}
    {% endif %}
{% endfor %}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号