我想要的内容:
我有名为 Book 和问题的模型类。在“书籍”中,有一个名为 quantity 的字段,用于定义其中有多少本书。
管理员向学生发行图书时,数量为 -1 。我该如何实施呢?
注意:我想在 Django Admin Dashboard
from django.db import models
from datetime import date, timedelta, datetime
# Create your models here.
class User(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
depertment_name = models.CharField(max_length=30)
roll_number = models.CharField(max_length=10, primary_key=True)
semester = models.CharField(max_length=10)
def __str__(self):
return self.depertment_name.upper() + ', ' + self.roll_number + ', ' + self.first_name.upper()
class Book(models.Model):
name = models.CharField(max_length=30)
author_name = models.CharField(max_length=30)
category = models.CharField(max_length=30)
quantity = 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 return_date(self):
return datetime.now()+timedelta(days=3)
def fine(self):
return_date = datetime.now() + timedelta(days=3)
if datetime.now() > return_date:
return 'Fine'
else:
return 'No Fine'
管理员代码
from django.contrib import admin
from django.contrib.auth.models import Group
from .models import User, Book, Issue
admin.site.site_header = 'Library Management System'
class UserAdmin(admin.ModelAdmin):
list_display = ('roll_number', 'first_name', 'last_name', 'depertment_name')
list_filter = ('depertment_name', 'semester')
search_fields = ('roll_number', 'first_name')
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', 'save')
list_filter = ('issue_date',)
search_fields = ('issue_id',)
admin.site.register(User, UserAdmin)
admin.site.register(Book, BookAdmin)
admin.site.register(Issue, IssueAdmin)
admin.site.unregister(Group,)
答案 0 :(得分:0)
我认为,重写save()
模型的 Issue
方法可以解决问题,
class Issue(models.Model):
# your code
def save(self, *args, **kwargs):
if not self.pk:
super().save(*args, **kwargs)
self.book_name.quantity -= 1
self.book_name.save()
else:
super().save(*args, **kwargs)
Update-1
为了查看书籍数量,请在book_name__quantity
的{{1}}中使用 list_display
。
IssueAdmin