我创建了一个
receiver function
应该更新模型的
total_likes
属性(基于
users_like
属性)每次用户单击特定图像的like按钮时。(这是《Django by Example》一书的一部分)。但字段的值始终保持不变,并且等于默认值0。即使我尝试在django的shell中手动为字段赋值,它也不会改变(“更新”部分中的代码示例)。
如果我做错了什么事,有人能帮我看看代码并指出正确的方向吗?
我正在使用Django 1.9。
# models.py
class Image(models.Model):
...
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='images_liked',
blank=True)
total_likes = models.PositiveIntegerField(default=5)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Image, self).save(*args, **kwargs)
# signals.py
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from .models import Image
@receiver(m2m_changed, sender=Image.users_like.through)
def users_like_changed(sender, instance, **kwargs):
instance.total_likes = instance.users_like.count()
instance.save()
# apps.py
from django.apps import AppConfig
class ImagesConfig(AppConfig):
name = 'images'
verbose_name = 'Image bookmarks'
def ready(self):
# import signal handlers
import images.signals
# __init__.py
default_app_config = 'images.apps.ImagesConfig'
更新:
当我从djangoshell运行下面的代码时,这会更改
总计_赞
值,但它看起来只是临时的:
from images.models import Image
for image in Image.objects.all():
print(image.total_likes)
image.total_likes = image.users_like.count()
print(image.total_likes)
image.save()
print(image.total_likes)
上述代码的输出:
0 #initial/default value of 0
3 #current number of users who like the picture
3