如何使用 Django ManyToMany 关系的“反向"? [英] How to use the 'reverse' of a Django ManyToMany relationship?

查看:30
本文介绍了如何使用 Django ManyToMany 关系的“反向"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自 Rails 背景,在使用 Django 中提供的关联方法"时遇到了一些麻烦.我有两个模型(为了简洁起见已经简化了),如下所示:

I'm coming from a Rails background, and am having a bit of trouble making use of the "Association Methods" provided in Django. I have two models (which have been simplified for the sake of brevity), like so:

class User(models.Model):
    username = models.CharField(max_length=100, unique=True)
    companies = models.ManyToManyField('Company', blank=True)

class Company(models.Model):
    name = models.CharField(max_length=255)

根据 Django 文档:

According to the Django documentation:

哪个模型具有 ManyToManyField 无关紧要,但您应该只将其放入其中一个模型中——而不是同时将其放入两个模型中.".

"It doesn't matter which model has the ManyToManyField, but you should only put it in one of the models -- not both.".

所以我明白,如果我有一个名为 user 的用户实例,我可以这样做:

So I understand that if I have an instance of a User, called user, I can do:

user.companies

我的问题是如何做相反的事情?如何获取属于 Company 实例的所有用户,例如 Company:

My question is how do I do the reverse? How do I get all users that belong to a Company instance, let's say Company:

company.users # This doesn't work!

这样做的惯例是什么?我读过的文档并没有真正涵盖这一点.我需要关联以两种方式工作,所以我不能简单地将它从一个模型移动到另一个模型.

What's the convention to do this? The documentation that I've read doesn't really cover this. I need the association to work both ways, so I can't simply move it from one model to the other.

推荐答案

company.user_set.all()

将返回属于特定公司的 User 对象的查询集.默认情况下,您使用 modelname_set 来反转关系,但您可以覆盖它,在定义模型时提供 related_name 作为参数,即

will return a QuerySet of User objects that belong to a particular company. By default you use modelname_set to reverse the relationship, but you can override this be providing a related_name as a parameter when defining the model, i.e.

class User(models.Model):
    companies = models.ManyToManyField(Company, ..., related_name="users")

> company.users.all()

这里是相关文档

这篇关于如何使用 Django ManyToMany 关系的“反向"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆