django 2 models.py

时间:2018-08-21 03:47:52

标签: python django django-models

我想在Book中通过Member定义Borrowmodels.py之间的关系

ER

但是我不知道如何定义Borrow关系。 在Borrow表中,必须确定谁借了哪些书,以及哪个日期归还了哪些书。我应该在该日期字段中使用其他表格吗?

models.py

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import gettext as _

class CategoryType(models.Model):
    category_name = models.CharField(max_length=200)
    def __str__(self):
        return self.category_name

class Book(models.Model):
    name = models.CharField(verbose_name="عنوان", max_length=128)
    number_of_copy = models.IntegerField(default=0)
    writer = models.CharField(max_length=64)
    B_category = models.ForeignKey(CategoryType, on_delete=models.CASCADE)
    class Meta:
        ordering = ["B_category"]
    def __str__(self):
        return self.name


class Borrow(models.Model):
    borrowed_from_date = models.DateField(_("borrow Date"), default=0)
    borrowed_to_date = models.DateField(_("return Date"), default=3)
    actual_return_date = models.DateField()
    borrowed_by = models.ForeignKey(member, on_delete=models.CASCADE)
    books = models.ManyToManyField(Book)
    def __str__(self):
        return self.id


class Member(AbstractUser):
   pass

我认为在Member类中,我应该有一个包含borrow_id的字段,但是如何?

1 个答案:

答案 0 :(得分:2)

在我看来,您需要将ManyToManythrough模型一起使用(这样,您可以为Borrow模型的每一行存储额外的信息)

...

class Borrow(models.Model):
    borrowed_from_date = models.DateField(_("borrow Date"), default=0)
    borrowed_to_date = models.DateField(_("return Date"), default=3)
    actual_return_date = models.DateField()
    borrowed_by = models.ForeignKey(Member, on_delete=models.CASCADE)
    book = models.ForeignKey(Book)
    def __str__(self):
        return self.id

...
class Member(AbstractUser):
    borrowed_books = models.ManyToManyField(Book, through='Borrow')

也许此链接(https://docs.djangoproject.com/es/2.1/ref/models/fields/#django.db.models.ManyToManyField.through)可以对其进行更多说明。