我有几个型号分别为 User , Book 和问题。型号 Book 中有一个名为 remaining 的字段,其中包含可用图书数量的值。
我想要的东西:
如果有 0 本书可用,则发行一本书会关闭。
models.py
from django.db import models
from datetime import date, timedelta, datetime
class Book(models.Model):
name = models.CharField(max_length=30)
author_name = models.CharField(max_length=30)
category = models.CharField(max_length=30)
remaining = models.IntegerField()
def __str__(self):
return self.name
class Issue(models.Model):
issue_id = models.CharField(max_length=10)
roll = models.ForeignKey(User, on_delete=models.CASCADE)
book_name = models.ForeignKey(Book, on_delete=models.CASCADE)
issue_date = models.DateField(auto_now=False, auto_now_add=True)
def save(self, *args, **kwargs):
if not self.pk:
super().save(*args, **kwargs)
if self.book_name.remaining > 0:
self.book_name.remaining -= 1
self.book_name.save()
elif self.book_name.remaining == 0:
print('hi')
else:
super().save(*args, **kwargs)
admin.py
from django.contrib import admin
from django.contrib.auth.models import Group
from .models import User, Book, Issue
class BookAdmin(admin.ModelAdmin):
list_display = ('name', 'author_name', 'remaining', 'category')
list_filter = ('category', 'author_name')
search_fields = ('name', 'author_name')
class IssueAdmin(admin.ModelAdmin):
list_display = ('issue_id', 'issue_date', 'return_date', 'fine',)
list_filter = ('issue_date',)
search_fields = ('issue_id',)
admin.site.register(Book, BookAdmin)
admin.site.register(Issue, IssueAdmin)
我想在管理信息中心中实施此操作
问候
答案 0 :(得分:1)
在清洁功能上,仅检查书籍是否可用。 如果没有可用的记录,则会引发验证错误。
def clean(self, *args, **kwargs):
from django.core.exceptions import ValidationError
super().clean()
if self.book_name.remaining < 1:
raise ValidationError("No books available")
else:
self.book_name.remaining -= 1
self.book_name.save()