【问题标题】:Checking if two Models belongs to a Many-to-Many relationship检查两个模型是否属于多对多关系
【发布时间】:2011-05-13 21:51:34
【问题描述】:

我在两个 Django 模型之间建立了多对多的关系:

from django.contrib.auth.models import User
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    ...
    bees = models.ManyToManyField('Bee')
class Bee(models.Model):
    ...

在我的模板中,我希望根据用户是否有特定的 Bees 有不同的输出。我现在正在做的是创建一个自定义过滤器,它执行类似这样的操作:

@register.filter
def my_filter(user, bee):
    userprofile = user.get_profile()
    return bee in userprofile.bees.all()

在模板中,我可以这样使用它:

{% for bee in bees %}
    {% if user|my_filter:bee %}
        I am in {{ bee }}
    {% else %}
        I am not in {{ bee }}
    {% endif %}
{% endfor %}

但这似乎很糟糕,因为 1) 我调用了 .all() -- 加载所有蜜蜂,包括我不感兴趣的蜜蜂 -- 不使用结果,2) 我认为我不需要创建一个自定义过滤器,因为这应该很常见

检查一个模型是否属于与另一个模型的多对多关系的正确方法是什么?

【问题讨论】:

  • 您的过滤器中应该包含什么“蜜蜂”?我想,“蜜蜂”与“蜜蜂”的关系是什么?
  • @Bryce Siedschlaw:bees 是 bee 的复数形式(我通常对容器(例如列表、字典)或数据库表使用复数名称,对非容器或数据库行使用单数名称。另外,我只是添加了一些更正以使问题不那么混乱(我为凌晨 4 点写信表示歉意)。

标签: django many-to-many


【解决方案1】:

如果您想检查您的模板,您可以查看in operator

{% if special_bee in profile_instance.bees.all %}
    This profile is related to this special bee.
{% endif %}

【讨论】:

    【解决方案2】:

    您可以在视图中获取用户的蜜蜂 ID 列表。像这样的:

    def view(request):
        user_bee_ids = request.user.bees.all().values_list('pk', flat=True)
    

    然后在你的模板中你可以这样做:

    {% if bee.pk in user_bee_ids %}
        I am in {{ bee }}
    {% else %}
        I am not in {{ bee }}
    {% endif %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      相关资源
      最近更新 更多