【问题标题】:Is this record related to me?这个记录和我有关吗?
【发布时间】:2011-06-11 18:50:45
【问题描述】:

我有两个相互关联的模型。举一个人为的例子,第一个是事物的列表,第二个是喜欢每件事的人的列表。

我想显示一个列表,如果我喜欢其中一个,那么在它旁边显示一个图标。

# in the models
class Things(models.Model):
    name = models.CharField(max_length = 100)

class Likes(models.Model):
    user = models.ForeignKey(User)
    thing = models.ForeignKey(Thing)

# in the view
@login_required
def list_of_things(request):
    things = things.objects.all()
    context = RequestContext(request, {'things': things})
    return render_to_response('thinglist.html', context)

# in the template
{% for thing in things %}
<li>{{ thing.name }}
  ## PSUEDO CODE HERE
  {% if I've liked this thing %}
  <img src="like.png">
  {% endif %}
</li>

我发现在 python shell 中我可以这样做:

>>> thing.likes_set.filter(user=user)

得到我想要的,但我不确定我应该把它放在上面的代码中的哪个位置。我想了一下,如果我在我的 Things 模型中添加一个方法,我可以在我的模板中执行以下操作:

{% if thing.liked_by_me %}

但这需要模型知道用户名。而且这似乎不是最好的表现。

有什么建议吗?

【问题讨论】:

    标签: django django-models foreign-key-relationship


    【解决方案1】:

    为了获得最佳性能,您可以获得一份清单和您喜欢的清单。

    def list_of_things(request):
        things = things.objects.all()
        things_i_like = Like.objects.filter(user=current_user).values_list('things', flat=True)
        context = RequestContext(request, {'things': things, 'things_i_like':things_i_like})
        return render_to_response('thinglist.html', context)
    

    values_list 只会选择“事物” flat 会将 QuerySet 展平为一个列表

    {% for thing in things %}
    <li>{{ thing.name }}
      ## PSUEDO CODE HERE
      {% if thing in things_i_like %}
       ## IMAGE LINK
      {% endif %}
    </li>
    {% endfor %}
    

    然后模板可以遍历 'things' 并检查单个事物是否在 'things_i_like' 列表中

    我还没有测试过,但它应该可以工作......

    【讨论】:

    • 谢谢,解决了。我最终得到了这样的代码:things_i_like = Likes.objects.filter(user=current_user).values_list('things__id', flat=False) 然后在我的模板中if thing.id in things_i_like。我很欣赏这个提示,以前从未使用过 values_list 功能。
    猜你喜欢
    • 2016-02-08
    • 2010-09-11
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多