开发者

Is this record related to me?

I have two models that are related to each other. For a contrived example, the first is a list of things and the second is a list of people who have liked each thing.

I want to show a list of things and if I've liked one of them then show an icon next to it.

# 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>

I've found that in the python shell I can do this:

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

and get what I want, but I'm not sure 开发者_开发百科where in the code above I should put this. I thought for a bit that if I added a method to my Things model I could, in my template, do:

{% if thing.liked_by_me %}

But that would require the model know the username. Also it seems like it wouldn't be the best performance.

Any suggestions?


In your view for best performance you can get a list of things and list of things you like.

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 will will only select only 'things' flat will flatten the QuerySet into a list

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

Then the template can iterate through 'things' and check if a single thing is in the 'things_i_like' list

I haven't tested this but it should work...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜