制作阅读清单并对模型之间的多对多关系感到困惑 - Django

Making a reading list and confused about ManyToMany relationship between the models - Django

我正在制作一个应用程序,用户可以在其中将书籍保存到 "reading" 列表中。我创建了 2 个模型来连接到我制作的自定义用户模型 (AbstractBaseUser)。

我正在学习如何执行此操作并且一直在阅读文档。

对于本书模型,这就是我所拥有的。我已经为用户创建了一个 ManyToMany 键,因为我希望这些书籍在输入到书籍数据库后能够被其他用户添加到他们的列表中。

书籍model.py

class Books(models.Model):
ONESTAR = "BD"
TWOSTAR = "OK"
THREESTAR = "GD"
FOURSTAR = "VG"
FIVESTAR = "EX"
DEFAULT = "NA"
READ  = "RB"
NOT_READ = "NR"
WANT_READ = "WR"

BOOK_REVIEW_CHOICES = (
    (DEFAULT, 'Rate Book'),
    (FIVESTAR, 'Excellent'),
    (FOURSTAR, 'Very Good'),
    (THREESTAR, 'Good'),
    (TWOSTAR,'Okay'),
    (ONESTAR, 'Bad'),
)

READ_BOOKS_CHOICES = (
    (READ,  'Read Book'),
    (NOT_READ, 'Didnt Read Book'),
    (WANT_READ, 'Want To Read')
    )

user = models.ManyToManyField(UsrAccounts, related_name='users')
title = models.CharField(max_length=300)
author = models.CharField(max_length=255)
description = models.CharField(max_length=500)
book_rating = models.CharField(max_length=2,choices=BOOK_REVIEW_CHOICES, default = DEFAULT)
read_status = models.CharField(max_length=2, choices=READ_BOOKS_CHOICES, default = READ)
image = models.ImageField(upload_to = user_directory_path, null= True, blank=True)
date_added = models.DateTimeField(auto_now=False, auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True, auto_now_add=False)

对于列表模型,我有一个外键用于列表和用户之间的多对一关系,但在列表和书籍之间有一个多对多关系。

我的列表Model.py

class MyList(models.Model):
user = models.ForeignKey(
    'accounts.UsrAccounts',
    on_delete=models.CASCADE)
title = models.CharField(max_length=500)
books = models.ManyToManyField(Books, related_name='books')

我设置对了吗?

如果我没理解错的话,你应该在 UserAccount 模型指向 Book 模型上设置 M2M 字段:

class UserAccount(models.Model):
    reading_list = models.ManyToManyField('Book', blank=True)

如果你想给阅读列表一个标题,你应该使用另一个模型来保存它,比如:

class UserAccount(models.Model):
    reading_list = models.ManyToManyField('Book', through='ReadingList')

class ReadingList(models.Model):
    user = models.ForeignKey('UserAccount')
    title = models.CharField(max_length=100)
    book = models.ForeignKey('Book')
    # some other fields related to a reading list

关于 through keyword on M2M field.

的 Django 文档

顺便说一句,不要在模型名称上使用复数形式,django 会在需要时添加复数形式。