简体   繁体   English

Django - 检查列表是否包含模板中的内容

[英]Django - check if list contains something in a template

I'm trying to check if an item is in a list (set) inside of a template. 我正在尝试检查项目是否在模板内的列表(集)中。

I've found this question here: Is it possible, in a django template, to check if an object is contained in a list 我在这里找到了这个问题: 在django模板中,是否有可能检查一个对象是否包含在列表中

however the solution isn't working for me. 但是解决方案对我不起作用。

I'm trying this: 我正在尝试这个:

{% if trip in request.user.trip_set.all %}

where trip is an instance of a Trip, user is a User, Trip has a ManyToManyField connecting it to User, through TripReservation 其中trip是Trip的一个实例,user是User,Trip有一个ManyToManyField通过TripReservation将它连接到User

class TripReservation(models.Model):
    user = models.ForeignKey(User)
    trip = models.ForeignKey(Trip)

class Trip(models.Model):
    members = models.ManyToManyField(User,blank=True,null=True,through='TripReservation')

request.user.trip_set.all is not a list but a queryset. request.user.trip_set.all不是列表而是查询集。 I think it is the reason of your problem. 我认为这是你问题的原因。 You can try to change that into a list with the dictsort template filter. 您可以尝试使用dictsort模板过滤器将其更改为列表。

{% if trip in request.user.trip_set.all|dictsort:"id" %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM