Django 计数对象字段



我需要创建一个字段来计算每个图书馆的注册书籍数量。

每本书都通过ForeighKey与图书馆相关

如果我注册或删除一本书,它应该会在与您自己的图书馆相关的"book_count"字段中自动更新。

库/模型.py

from django.db import models
class Libraries(models.Model):
name = models.CharField(max_length=50)
book_count = models.IntegerField(default=0)
def __str__(self):
return self.name

书籍/模型.py

from django.db import models
from libraries.models import Libraries
class Books(models.Model):
library = models.ForeignKey(Libraries, on_delete=models.DO_NOTHING, blank=True, null=True)
book = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.book

如何在每个图书馆的模型中创建这个简单的图书计数器?

给定以下应用程序

$ tree -L 2
.
├── db.sqlite3
├── libraryapp
│   ├── __init__.py
│   ├── __pycache__
│   ├── admin.py
│   ├── migrations
│   ├── models.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py    

和你的模型(我做了一点重构(

$ cat libraryapp/models.py 
from django.db import models
class Library(models.Model):
name = models.CharField(max_length=50)
book_count = models.IntegerField(default=0)
def __str__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
library = models.ForeignKey(Library, on_delete=models.DO_NOTHING, blank=True, null=True)
def __str__(self):
return self.name
def save(self):
super().save()
self.update_book_count()
def delete(self):
super().delete()
self.update_book_count()
def update_book_count(self):
if self.library:
self.library.book_count = self.library.book_set.count()
self.library.save()

您可以按如下方式获取某个图书馆中的书籍数量:

$ python3 manage.py shell
>>> from libraryapp.models import Book, Library
>>> library = Library.objects.first()
>>> library.book_count
1

请注意,这假定更新库书籍数量的唯一方法是添加或删除书籍。

我使用信号得到了它。

@receiver(post_save, sender=Book)
def add_book_count(instance, created, **kwargs):
if created:
instance.library.book_count += 1
instance.library.save()

@receiver(post_delete, sender=Book)
def rem_statement_count(instance, **kwargs):
instance.library.book_count -= 1
instance.library.save()

相关内容

  • 没有找到相关文章

最新更新