如何使用“反向”的Django ManyToMany关系? [英] How to use the 'reverse' of a Django ManyToMany relationship?
问题描述
class User(models.Model) :
username = models.CharField(max_length = 100,unique = True)
companies = models.ManyToManyField('Company',blank = True)
class公司(型号。模型):
name = models.CharField(max_length = 255)
根据Django文档:
ManyToManyField的模型并不重要,但您应该将其放在其中一个模型中,而不是两个。
所以我明白,如果我有一个用户的实例,称为用户,我可以做:
user.companies
我的问题是我如何做相反的事情?如何获得属于公司实例的所有用户,假设公司:
company.users#这不工作!
做什么约会?我已阅读的文档并没有真正涵盖这一点。我需要协会工作的两种方式,所以我不能简单地将它从一个模型移动到另一个模型。
company.user_set.all()
将返回一个用户
属于特定公司的对象。默认情况下,您可以使用 modelname_set
来扭转关系,但是您可以重写此定义时提供 related_name
作为参数模型,即
class User(models.Model):
companies = models.ManyToManyField(User,.. 。,related_name =users)
> company.users.all()
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)
According to the Django documentation:
"It doesn't matter which model has the ManyToManyField, but you should only put it in one of the models -- not both.".
So I understand that if I have an instance of a User, called user, I can do:
user.companies
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()
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(User, ..., related_name="users")
> company.users.all()
here is the relevant documentation
这篇关于如何使用“反向”的Django ManyToMany关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!