【问题标题】:Django ManyToMany realtionship doesn't workDjango ManyToMany realtionship 不起作用
【发布时间】:2015-10-26 20:52:51
【问题描述】:

我正在尝试在我的 models.py 中执行此操作:

class Tag(models.Model):
    ''' snip '''
    name = models.CharField(max_length=30)

class Stuff(models.Model):
    kind = models.CharField(max_length=30)
    tag = models.ManyToManyField(Tag)

但是当我从 shell 中的 Stuff 进行查询时,关系字段返回“无”,如下所示:

>>> q = Stuff.objects.all()
>>> p = q.tag.name
>>> print q.tag.name
None

我也不能在我的模板中使用这个键。

数据库后端是mysql。

有什么问题?

【问题讨论】:

    标签: python mysql django django-models models


    【解决方案1】:

    你可以像这样调用多对多关系,

    q = Stuff.objects.all()
    for p in q.tag.all():
       print p.name
    

    在 HTML 中

    {%for tag in stuff.tag.all %}
    {{ tag.name }}
    {% endfor %}
    

    【讨论】:

      【解决方案2】:

      目前尚不清楚您希望模型如何工作。你想让 Stuff 有一个单个标签还是几个标签?

      两种情况的解决方案如下。

      Stuff 对象有很多标签的情况

      这里有一些错误。

      1. 在您的示例中,变量 q 不是 Stuff 对象,因此您不能询问它的属性。这是queryset。就像其他答案一样,您必须像列表一样遍历它。
      2. ManyToMany 关系意味着 Stuff 将有许多标签,但您使用它时就像 Stuff 只有一个标签一样。

      一个例子(我将用Stuff.tags 替换Stuff.tag,因为将其称为单个标签会产生误导):

      # Get the first stuff
      >>> stuff = Stuff.objects.first()
      # Access the attribute `tag`. Notice it's NOT a Tag, but a `RelatedManager`.
      >>> stuff.tag
      <django.db.models.fields.related.ManyRelatedManager object at 0x7fe2a3e5cc10>
      # which you can use as a queryset!!
      >>> stuff.tag.all()
      [<Tag: tag1>, <Tag: tag2>, ...]
      # Then you can iterate through it, filter or whatever
      >>> stuff.tag[0]
      <Tag: tag1>
      >>> stuff.tag[0].name
      u'tag1'
      

      Stuff 对象只有一个 Tag 的情况

      如果您希望 Stuff 只有一个 Tag 对象,您必须像这样声明它。

      tag = models.OneToOneField(Tag)
      

      现在您可以使用stuff.tag.name 并像在模板中那样使用它。如果你想要很多标签,你必须像这样遍历 Stuff 的标签(同样,我在这个例子中使用标签而不是标签):

      {% for tag in stuff.tags %}
          {{ tag.name }}
      {% endfor %}
      

      当然还有其他方法,比如使用过滤器join

      {# Print the tag names joined by ', ' #}
      {{ stuff.tags.all|join:', ' }}
      

      【讨论】:

        猜你喜欢
        • 2016-01-02
        • 2018-02-09
        • 2018-01-12
        • 2021-02-23
        • 2022-01-26
        • 2018-01-25
        • 1970-01-01
        • 2020-03-17
        • 1970-01-01
        相关资源
        最近更新 更多