Django如何迭代模板中两个子类的查询集? [英] Django how to iterate querysets of two subclasses in template?

查看:58
本文介绍了Django如何迭代模板中两个子类的查询集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 django-model-utils 用于继承管理器。我想用一个字典获得两个子类的结果,而又没有重复。

I am using django-model-utils for inheritance Managers. I want to get result of both sub-classes with one dictionary without getting duplicates.

class Images(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created', on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    objects = InheritanceManager()

class Postimg(Images):
    user_img= models.ImageField(upload_to='images/%Y/%m/%d', null=True, blank=True)


class Postsms(Images):
    user_message = models.CharField(max_length=500,blank=True)


views.py


def home(request):
    all_post = Images.objects.all().order_by('-created').select_subclasses()
    return render(request, 'copybook/home.html',{ 'all_post':all_post})


copybook / home.html


{% for foo in all_post %}
    <hr>
    <br> SMS by:  <p>{{ foo.user}}  __  {{ foo.created }}</p>
    <h2>{{ foo.user_message }}</h2>
    <hr>
    <br> IMAGE by:  <p>{{ foo.user}}  __  {{ foo.created }}</p> 
    <img src="{{ foo.user_img.url }}"width="250">
{% endfor %}

我期望在上传图片或邮件时获得的结果应该达到最高主页,但是现在当我上传图像时,空白消息也会被迭代。

I expect the result when I upload an image or message that should get top at home page, but now when I upload an image, a blank message also gets iterated.

我认为问题出在我的home.html中,因为我不知道如何迭代
在两个子类中,并且具有一个for循环而没有重复。

I think the problem is in my home.html, because I do not know how to iterate over two sub-classes with a single for loop without getting duplicates.

推荐答案

在您的模板中,您正在处理每个项目好像它既是消息又是图像。这就是为什么消息的图像部分为空,消息的图像部分为空。

In your template, you are processing every item as if it were both a message and an image. That's why you get empty image sections for messages and empty message sections for images.

最简单的解决方法是检查 user_img user_message 计算为 True

The simplest workaround would be to check if user_img or user_message evaluates to True:

{% for foo in all_post %}
    <hr>
    {% if foo.user_message %}
        <br> SMS by:  <p>{{ foo.user}}  __  {{ foo.created }}</p>
        <h2>{{ foo.user_message }}</h2>
    {% else %}
        <br> IMAGE by:  <p>{{ foo.user}}  __  {{ foo.created }}</p> 
        <img src="{{ foo.user_img.url }}"width="250">
    {% endif %}
{% endfor %}

而不是 else ,您可以单独执行 if foo.user_img 以避免将带有空消息的消息对象解释为图像。

Instead of else you can do a separate if foo.user_img to avoid message objects with empty messages to be interpreted as images.

这篇关于Django如何迭代模板中两个子类的查询集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆