首页 > 解决方案 > 如何在 1 个 Django 模板中使用 2 个模型的相关名称

问题描述

嗨 Djangonauts 我是 Django 新手,所以如果我的逻辑或代码中有愚蠢的错误,请原谅我。我有 4 个模型。用户、组、发布和证明。

用户只是一个普通的用户模型

是主题(例如:自行车、篮球、划独木舟……)用户选择哪个组并在该组中写一篇文章。

帖子:帖子就像作者展示如何做的“任务”。(例如:如何在一个轮子上骑自行车......)。最后一个模型是证明模型,其他用户回应说他们做了帖子解释的操作。

证明:当其他用户按照帖子所说的去做时。他们有 2 张上传 2 张图片点击提交,他们的名字被添加到完成“任务”的成员中

下面是我的证明 models.py

用户 = get_user_model()

class Proof(models.Model):
    user = models.ForeignKey(User, related_name='proofmade')
    post = models.ForeignKey(Post, related_name='postproofmade')
    made_at = models.DateTimeField(auto_now=True)
    image_of_task= models.ImageField()
    proof_you_made_it = models.ImageField()
    suggestions = models.CharField(max_length=1000)

下面是我的 post.models.py

class Post(models.Model):
    user = models.ForeignKey(User, related_name='posts')
    group = models.ForeignKey(Group, related_name='posts')
    title = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(allow_unicode=True, unique=True)
    message = models.TextField()
    post_image = models.ImageField()
    made = models.ManyToManyField(User, blank=True, related_name='post_made')

下面是我的 post_detail 视图

class PostDetail(SelectRelatedMixin, DetailView):
    model = Post
    select_related = ('user', 'group')

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(user__username__iexact=self.kwargs.get('username'))

下面是我的post_detail 模板(这就是问题所在)

{% if user in post.made.all %}
    {% for proof in post.postproofmade.all %} #I know I am referencing the related_name incorrectly. I have tried various options none seem to work 
    <a href="{% url 'proof:proof_delete' slug=post.slug pk=proof.pk %}">
        <img src="{% static 'images/thumbs_up_yes.png' %}" height="25px">
    </a><br/>
    {% endfor %}
    {% else %}
    <a href="{% url 'proof:new_proof' slug=post.slug %}">
        <img src="{% static 'images/thumbs_up_no.png' %}" height="25px">
    </a><br/>
{% endif %}

我刚刚意识到这段代码可能存在一个小问题。如果有 2 人执行该任务,则竖起大拇指的图像显示 2 次。如果 3 个人来做这个任务。竖起大拇指的图像将显示 3 次。我不想那样。竖起大拇指的图像应该只显示一次。

如果用户不是执行任务的成员之一,则它会正确显示。或者如果用户是匿名用户,即使它显示正确。(请参阅下面的问题图片)

竖起大拇指是一个类似于“facebook like”的切换按钮,只是它有一个表格,可以添加 2 张图像来证明你做到了,并删除了将你从完成任务的人列表中删除的证明。此功能运行良好

{% for user in user.proofmade.all | slice:":1" %} #This gets the job done 
#But I am afraid its not production worthy. I would love a actual solution. If 
#not can someone tell me. What are the bad effects of using this 
#If there are 10,000 people who do the task will the forloop run 
#10,000 times and show just 1 result?

在此处输入图像描述 在此处输入图像描述

标签: pythondjangodjango-modelsdjango-templatesdjango-views

解决方案


推荐阅读