简体   繁体   English

Django:如何获取与列表相关的ForeignKey记录?

[英]Django: how to get list related ForeignKey records?

I am using Django v1.11. 我正在使用Django v1.11。 Here are 2 models: 这是2种型号:

class Task(models.Model):
    title = models.CharField()

class TaskUser(models.Model):
    task = models.ForeignKey(Task, related_name='task_user')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='+')

So, I want to get list of tasks and print in one column list of users that are related to this task. 因此,我想获取任务列表并在与该任务相关的用户的一列列表中打印。 How to do that? 怎么做? The problem is tried a lot: select_related , prefetch_related('task_user') and so on.. but nothing works. 问题是尝试了很多: select_relatedprefetch_related('task_user')等等..但没有任何工程。 In some cases there are no sql error, but it prints task.User.None 在某些情况下,没有sql错误,但会打印task.User.None

tasks = Task.objects.all()

View must be: 视图必须是:

<table>
<tr>
    <td>Title</td>
    <td>Users</td>
</tr>
{% for task in tasks %}
<tr>
    <td>{{ task.title }}</td>
    <td>
    {% for user in task.users %}
        {{ user.id }}
    {% endfor %}
    </td>
</tr>
{% endfor %}
</table>

Add a many-to-many field to Task, using the through model you already have: 使用现有模型,将多对多字段添加到任务中:

class Task(models.Model):
    users = models.ManyToManyField(settings.AUTH_USER_MODEL, through='TaskUser')

and use .all when iterating: 并在迭代时使用.all

{% for user in task.users.all %}
    {{ user.id }}
{% endfor %}

(Note, you should remove the related_name='+' from the TaskUser.user field.) (注意,您应该从TaskUser.user字段中删除TaskUser.user related_name='+' 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Django中获取所有ForeignKey的列表 - How to get a list of all ForeignKey's in django 如何在Django的同一模型中获取与ForeignKey相关的主键(pk)? - How to get the foreignKey related primary key (pk) in the same model in django? 如何在Django模型ForeignKey和OneToOneField中获取所有相关对象 - How to get all related objects in django model ForeignKey and OneToOneField Django OneToOneField &amp; Foreignkey - 如何从相关模型中获取价值? - Django OneToOneField & Foreignkey - How to get value from related model? Django Admin list_display添加列[相关ForeignKey的计数记录] - Django Admin list_display add column [count records of related ForeignKey] 如何获得外键关联的模型计数 - how to get the count of model related by foreignkey 在Django中获取与此模型相关的所有模型(通过ForeignKey,ManyToMany) - Get all models related to this model in django (via ForeignKey, ManyToMany) 如何通过Django中的另一个ForeignKey使用ForeignKey字段获取对象? - How to get objects using a ForeignKey field through another ForeignKey in Django? Django:如何根据一个ForiegnKey进行查询,并显示每个ForeignKey的相关数据? - Django: How to query based on a ForiegnKey and display related data for each ForeignKey? Django:如何在Abstract Model class中设置ForeignKey related_name? - Django: how to set ForeignKey related_name in Abstract Model class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM