[英]Django ManyToMany realtionship doesn't work
I'm trying to do this in my models.py: 我正在尝试在我的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)
But when I make query from Stuff in shell the relationship fields return 'None' like this: 但是,当我从外壳中的Stuff进行查询时,关系字段将返回“ None”,如下所示:
>>> q = Stuff.objects.all()
>>> p = q.tag.name
>>> print q.tag.name
None
I can't use this keys in my template too. 我也不能在模板中使用此键。
Database backend is mysql. 数据库后端是mysql。
What is the problem? 问题是什么?
You can call many to many relation like this, 您可以像这样调用多对多关系,
q = Stuff.objects.all()
for p in q.tag.all():
print p.name
In HTML 在HTML中
{%for tag in stuff.tag.all %}
{{ tag.name }}
{% endfor %}
It's unclear how exactly you want your models to work. 尚不清楚您希望模型如何工作。 Do you want Stuff to have a single Tag or several Tags?
您是否要让Stuff具有单个标签或几个标签?
Solutions for both case uses follow. 两种情况的解决方案如下。
There are some mistakes here. 这里有一些错误。
q
isn't a Stuff object, so you can't ask for it's attributes. q
不是Stuff对象,因此您不能要求它的属性。 It's a queryset . An example (I'm going to replace Stuff.tag
by Stuff.tags
, since it's misleading to call it a single tag): 一个例子(我要去取代
Stuff.tag
由Stuff.tags
,因为它误导称之为一个标签):
# 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'
If you want Stuff to have only ONE Tag object you have to declare it like this. 如果您希望Stuff仅具有一个Tag对象,则必须这样声明它。
tag = models.OneToOneField(Tag)
NOW you can do stuff.tag.name
and use it like that in the template. 现在,您可以执行
stuff.tag.name
并像在模板中那样使用它。 If you want many Tags you'll have to iterate through the Stuff's Tags like this (again, I'm using tags instead of tag for this example): 如果您想要许多标签,则必须像这样遍历Stuff的标签(同样,在此示例中,我使用的是标签而不是标签):
{% for tag in stuff.tags %}
{{ tag.name }}
{% endfor %}
There are of course other ways, like using the filter join
当然还有其他方法,例如使用过滤器
join
{# Print the tag names joined by ', ' #}
{{ stuff.tags.all|join:', ' }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.