限制每个用户对每本书的单一评级:Django ORM

Restricting single Rating on each Book by each User : Django ORM

Edited Title : Limit multiple "Many to One" fields into "One to One" association : Django

我们已经 BookUserRating 作为 Django 模型。

书本

class Book(models.Model):
    isbn = models.CharField(max_length=32)
    title = models.CharField(max_length=256)

    def __str__(self):
        return self.title 

图书评级

class BookRating(models.Model):
    book = models.ForeignKey(Book, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    rating = models.SmallIntegerField(choices=[(i, i) for i in range(1, 6)])

    def __str__(self):
        return self.rating

问题陈述

我如何确保每个用户对每本书至多一个评价

随心所欲

class BookRating(models.Model):
    book = models.ForeignKey(Book, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    rating = models.SmallIntegerField(choices=[(i, i) for i in range(1, 6)], default=1)

    class meta:
        unique_together = ('book','user')

您的模型确实实现了多对多关系,但是您无法完全访问 django ManyToMany 功能。我建议你这样做:

class Book(models.Model):
    isbn = models.CharField(max_length=32)
    title = models.CharField(max_length=256)
    ratings = models.ManyToManyField(User,through='BookRating')

执行此操作时,您的 BookRating 可以保持不变,但对 Book 模型的小改动可让您完全访问此处描述的 api:https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many/

有趣的是,如上所述修改 Book 模型不会对数据库中的 table 结构进行任何更改。它们保持不变。只需解锁 api.