簡體   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