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

时间:2022-05-14 21:07:12

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')

1 个解决方案

#1


1  

request.user.trip_set.all is not a list but a queryset. I think it is the reason of your problem. You can try to change that into a list with the dictsort template filter.

request.user.trip_set.all不是列表而是查询集。我认为这是你问题的原因。您可以尝试使用dictsort模板过滤器将其更改为列表。

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

#1


1  

request.user.trip_set.all is not a list but a queryset. I think it is the reason of your problem. You can try to change that into a list with the dictsort template filter.

request.user.trip_set.all不是列表而是查询集。我认为这是你问题的原因。您可以尝试使用dictsort模板过滤器将其更改为列表。

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