在Django ORM中更改其他表时更新表

时间:2018-07-18 02:54:58

标签: python django

Models.py

# store the number of new Videos that added to a Album
class Badge(models.Model):
    user_id = models.IntegerField()  # the user you wanna inform
    album_id = models.IntegerField()
    count = models.IntegerField(blank=True, null=True)
    update_time = models.DateTimeField(blank=True, null=True)

# a Album has several videos in it, and will be updated 
class Album(models.Model):
    title = models.CharField(max_length=100, default='', null=True)
    update_time = models.DateTimeField(blank=True, null=True)

class Video(models.Model):
    title = models.CharField(max_length=100, default='', null=True)
    aid = models.ForeignKey(Album, on_delete=models.CASCADE, default='')
    update_time = models.DateTimeField(blank=True, null=True)

假设在数据库中:

相册表:

357 Learning_Django 2018-07-02 12:40:03.041558

视频表:

1 Install_Python 357 2018-07-02 12:40:03.041558
2 Install_pip 357 2018-07-02 12:40:03.041558
3 Install_Django 357 2018-07-02 12:40:03.041558

现在,两个新视频已插入视频表中:

1 Install_Python 357 2018-07-02 12:40:03.041558
2 Install_pip 357 2018-07-02 12:40:03.041558
3 Install_Django 357 2018-07-02 12:40:03.041558
4 Create_Django_Project 357 2018-07-13 08:40:03.041558
5 Define_Django_Models 357 2018-07-13 08:40:03.041558

我该怎么做才能使此更新反映在Badge表上(插入/更新记录),像这样:

1 001 357 2 2018-07-13 08:40:03.041558

这意味着专辑#357已更新为2个视频,并将通知用户#001。

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

我认为信号就是您所需要的,演示这样

signals.py

from django.db.models.signals import post_save
from django.dispatch import receiver

from .models import User, Video, Badge

@receiver(post_save, sender=Video)
def create_badge(sender, instance=None, created=False, **kwargs):
    if created:
        badge, is_created = Badge.objects.get_or_create(user_id='user id you want inform', album_id=instance.aid.id, defaults={'count': 0})
        badge.count += 1
        badge.save()

apps.py

from django.apps import AppConfig


class UserConfig(AppConfig):
    name = 'user'

    def ready(self):
        import user.signals

__init__.py

default_app_config = 'user.apps.UserConfig'

将用户或用户更改为您自己的app_name

答案 1 :(得分:1)

正如@Ykh所说,信号是最好的方法。

您还可以使用模型的save方法。您可以在docs

中查看更多详细信息

这里是演示(实际上我不明白您想做什么,因此仅供参考)

class Video(models.Model):
    title = models.CharField(max_length=100, default='', null=True)
    aid = models.ForeignKey(Album, on_delete=models.CASCADE, default='')
    update_time = models.DateTimeField(blank=True, null=True)

    def save(self, *args, **kwargs):
        # do this only when created
        if not self.pk:
            # do something you want like
            badge, is_created = Badge.objects.get_or_create(user_id='user id you want inform', album_id=self.aid.id, defaults={'count': 0})
            badge.count += 1
            badge.save()
        super().save(*args, **kwargs)