检查项目是否包含在ManyToManyField(django)中(Checking if an item is contained in a ManyToManyField (django))

编程入门 行业动态 更新时间:2024-10-27 02:27:23
检查项目是否包含在ManyToManyField(django)中(Checking if an item is contained in a ManyToManyField (django))

所以我在Item1和Item2之间有一个ManyToManyField关系。 在网页上,我想根据两个项目是否连接显示两条消息之一。 我只是不确定如何使用{%if%}模板标记查询我的确切项目。

我正在寻找的是什么

{% if Item1 is connected to Item2 %} Display Message1 {% else %} Display Message2 {% endif %}

关于我如何完成这些工作的任何提示?

class Profile(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length=50) eventList = models.ManyToManyField(Event, blank="TRUE", null="TRUE", related_name='event_set+') def __unicode__(self): return self.name

So I have a ManyToManyField relationship between Item1 and Item2. On a webpage, I want to display one of two messages based on whether the two items are connected or not. I'm just not sure how to query my exact item using the {% if %} template tag.

Roughly what I'm looking for is

{% if Item1 is connected to Item2 %} Display Message1 {% else %} Display Message2 {% endif %}

Any tips on how I'd get this done?

class Profile(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length=50) eventList = models.ManyToManyField(Event, blank="TRUE", null="TRUE", related_name='event_set+') def __unicode__(self): return self.name

最满意答案

我仍然不清楚如果连接到其他对象,您希望看到哪个对象,但如果您想知道某个用户是否处于特定事件中,您可以这样做:

{% if event in user.eventList.all %} Display Message1 {% else %} Display Message2 {% endif %}

在现代django版本的条件下,您可以使用operator in 。

希望这可以帮助!

It still not clear to me what object you want to see if connected to other but if you want to know if a user is in an specific event you can do it like this:

{% if event in user.eventList.all %} Display Message1 {% else %} Display Message2 {% endif %}

You can use operator in in if conditions in modern django versions.

Hope this helps!

更多推荐

本文发布于:2023-08-01 13:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1360103.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:项目   ManyToManyField   django   contained   item

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!