繁体   English   中英

如何连接 Django Model 与多对多关系?

[英]How to Connect a Django Model with ManyToMany Relationship?

我正在制作一个与 django 中的谷歌教室非常相似的应用程序。

我有一个课程 model 和一个作业 model,我想将一个作业连接到指定的课程。

这些是我的模型

class Assignment(models.Model):
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    date_created = models.DateTimeField(default=timezone.now)


class Course(models.Model):
    title = models.CharField(max_length=100)
    subject = models.CharField(max_length=100)
    image = models.ImageField(default='no_course_image.jpg', upload_to='course_images')
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    students_invited = models.ManyToManyField(User, null=True, blank=True)
    assignments = models.ManyToManyField(Assignment, null=True, blank=True)
    date_published = models.DateTimeField(default=timezone.now)

    class Meta:
        verbose_name_plural = 'Course'
        ordering = ['-date_published']
    
    def __str__(self):
        return '{} - {}'.format(self.title, self.owner)

但是,当我使用 ForeignKey 在作业 model 中指定课程字段时出现错误? 您能否帮助我了解如何将作业连接到课程模型? 谢谢

When you try to create the Model Assignment with reference to the model Course , the Course Model has not yet created and vice versa and you will get an error either of the model is not defined

  1. 你可以使用它的引号
class Assignment(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE) name = models.CharField(max_length=100) date_created = models.DateTimeField(default=timezone.now)
  1. 您可以通过 model 使用自定义在此处输入链接描述

ForeignKey用于设置多对一关系。 正如您在Django 文档中看到的那样,当您尝试设置ManyToManyField时,它在这种情况下不起作用

ForeignKey¶

class ForeignKey(to, on_delete, **options)¶
A many-to-one relationship. Requires two positional arguments: 
the class to which the model is related and the on_delete option.

事实上,您甚至不需要在Assignment Model 中设置关系,因为 Django 将负责创建第三个表,通过它们的主键将两者链接在一起。 您可以在文档中看到这一点

from django.db import models

class Publication(models.Model):
    title = models.CharField(max_length=30)

    class Meta:
        ordering = ['title']

    def __str__(self):
        return self.title

class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication)

    class Meta:
        ordering = ['headline']

    def __str__(self):
        return self.headline

所以每次你像这样将作业添加到课程中

>>> c1 = Course(title='Python Course')
>>> c1.save()
>>> a1 = Assignment(name='Python Assignment')
>>> a1.save()
>>> c1.assignments.add(a1)

并且关系将自动创建,并且c1.assignments.all()将返回链接到课程的所有作业

如果您需要 go 反过来,那么您将使用a1.course_set.add(c1) 当使用没有与ManyToManyField object 绑定的 model 时,您需要使用*_set表示法,其中*将替换为小写的 model 名称。 可以在此处的文档中阅读有关相关对象引用的更多信息

我想课程 model 必须在作业 model 之前编写。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM