我希望,我正确地写了标题......)))
我有模型IndexOutOfBoundsException
,可以通过article
字段连接到用户。
ManyToMany
我可以列出通过以下方式连接到该模型的所有用户:
from django.db import models
from django.contrib.auth.models import User
from django.db import models
class Article(models.Model):
class Meta():
db_table = 'article'
article_users = models.ManyToManyField(User, null=True, blank=True, default=None)
article_title = models.CharField(max_length=200, blank=False, null=False)
article_content = models.IntegerField(choices=CONTENT_CHOICES, null=True, blank=True)
但是如何列出当前用户连接到的所有模型?
答案 0 :(得分:1)
你不能在你的观点中写出这样的东西:
Article.objects.filter(article_users=current_user)
或者请求是否必须在模板中?
答案 1 :(得分:1)
这就是你要找的东西吗?
{% for article in user.article_set.all() %}
{{article.article_title}}
{% endfor %}
如果用户是匿名的,也许您需要阻止此代码:
{% if user.is_authenticated() %}
{% for article in user.article_set.all() %}
{{article.article_title}}
{% endfor %}
{% else %}
# Do something for anonymous users.
{% endif %}
修改:将user.user替换为用户