[英]Is it best practice to define a join table for Django many to many relationships?
I have the following code:我有以下代码:
class Tutors(models.Model):
first_name = models.CharField(max_length=20, default=None, blank=False) #you need to add default none and blank false to enforce the Not-Null constraint
last_name = models.CharField(max_length=20, default=None, blank=False)
email = models.EmailField(max_length=254,default=None, blank=False)
birth_day = models.DateField(auto_now=False, auto_now_add=False, default=False, blank=False)
def __str__(self):
return(self.first_name + ' ' + self.last_name)
class ArtSubjects(models.Model):
subject_name = models.CharField(max_length=20, default=None, blank=False)
tutors = models.ManyToManyField(Tutors)
def __str__(self):
return self.subject_name
My question is, should I define many to many relationships like this?我的问题是,我应该像这样定义多对多关系吗? Or should I define a new class for the table?
或者我应该为表定义一个新类?
The reason I ask is that I can get objects from the join table by querying by ArtSubjects class like so - adobeAI.tutors.all()
returns <QuerySet [<Tutors: Matt Aird>, <Tutors: Tom John>]>
我问的原因是我可以通过 ArtSubjects 类这样查询来从连接表中获取对象 -
adobeAI.tutors.all()
返回<QuerySet [<Tutors: Matt Aird>, <Tutors: Tom John>]>
But I can't think of a way for querying the join table by tutors to see what classes an individual tutor teaches.但是我想不出一种方法可以通过导师查询联接表来查看个别导师教什么课。
Any advice on this?对此有何建议?
You can query tutors the same way.你可以用同样的方式查询导师。 Here's an axample:
这是一个例子:
john = Tutors.objects.get(first_name="John")
john.artsubjects_set.all()
If you like to have a more readable name than _set
, add a related_name
on the ManyToManyField field:如果你想有一个比更可读的名字
_set
,加related_name
在ManyToManyField字段:
class ArtSubjects(models.Model):
tutors = models.ManyToManyField(Tutors, related_name="teaches")
...
john.teaches.all()
You can find more details in the documentation https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/您可以在文档https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/ 中找到更多详细信息
This can be done (see https://docs.djangoproject.com/en/3.2/topics/db/models/#extra-fields-on-many-to-many-relationships ), but if you're not adding additional data to the intermediary model I wouldn't recommend it.这可以完成(参见https://docs.djangoproject.com/en/3.2/topics/db/models/#extra-fields-on-many-to-many-relationships ),但如果您不添加额外的中间模型的数据我不推荐它。
Django will create the intermediary model behind the scenes. Django 将在幕后创建中介模型。 In this case it would be accessible as
ArtSubjects.tutors.through
.在这种情况下,它可以作为
ArtSubjects.tutors.through
访问。
See @Marco's answer for how to query the relationship.有关如何查询关系的信息,请参阅@Marco 的回答。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.