获取当前用户连接到的所有模型的列表
Get the list of all the models, that current user connected to
我希望我写的标题是对的...)))
我有模型 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)
我可以列出通过以下方式在模板中连接到该模型的所有用户:
{% for user in article.article_users.all %}
{{ user.username }}
{% endfor %}
但是如何列出当前用户连接到的所有模型?
你能不能在你的观点中写下这样的东西:
Article.objects.filter(article_users=current_user)
还是请求必须在模板中?
这是您要找的吗?
{% 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 %}
编辑:将request.user替换为用户
我希望我写的标题是对的...)))
我有模型 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)
我可以列出通过以下方式在模板中连接到该模型的所有用户:
{% for user in article.article_users.all %}
{{ user.username }}
{% endfor %}
但是如何列出当前用户连接到的所有模型?
你能不能在你的观点中写下这样的东西:
Article.objects.filter(article_users=current_user)
还是请求必须在模板中?
这是您要找的吗?
{% 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 %}
编辑:将request.user替换为用户