制作阅读清单并混淆模型之间的ManyToMany关系 - Django

时间:2016-01-25 19:01:52

标签: django django-models manytomanyfield

我正在创建一个应用,用户可以将图书保存到"阅读"名单。我创建了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)

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

my List 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')

我做对了吗?

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您应该在UserAccount型号上设置Book字段指向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

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

from scipy.spatial import distance_matrix
loc = df[['X','Y']].values
dist_mat = distance_matrix(loc, loc)

from scipy.spatial.distance import cdist
dist_mat = cdist(loc, loc)

关于through keyword on M2M field的Django doc。

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