[英]How can I implement post_save signals in Django?
I am currently building a geolocation app, and I'm somewhat stuck somewhere.我目前正在构建一个地理定位应用程序,但我有点卡在某个地方。 I'm trying to implement a post_save Django signals in this code, but I can't figure out what exactly I need to do.
我正在尝试在此代码中实现 post_save Django 信号,但我无法弄清楚我到底需要做什么。 any help here would be appreciate.
这里的任何帮助将不胜感激。 Here's my code:
这是我的代码:
from ipaddress import ip_address
from django.contrib.auth import get_user_model从 django.contrib.auth 导入 get_user_model
from celery import shared_task from apps.users.abstractapi import AbstractAPI从 celery 导入 shared_task 从 apps.users.abstractapi 导入 AbstractAPI
User = get_user_model()用户 = get_user_model()
@shared_task def enrich_user(user_pk): user = User.objects.get(pk=user_pk) api = AbstractAPI() @shared_task defenrich_user(user_pk): user = User.objects.get(pk=user_pk) api = AbstractAPI()
location_details = api.get_geolocation_details(ip_address=user.ip_address)
if location_details is not None:
user.country = location_details.get("country")
user.country_code = location_details.get("country_code")
user.country_geoname_id = location_details.details.get("country_geoname_id")
user.longitude = location_details.get("longitude")
user.latitude = location_details.get("latitude")
user.save(update_fields=("country", "country_code", "country_geoname_id", "longitude", "latitude"))
holiday_details = api.get_holiday_details(
country_code=user.country_code,
day=user.date_joined.day,
month=user.date_joined.month,
year=user.date_joined.year,
)
if holiday_details is not None and any(holiday_details):
user.joined_on_holiday = True
user.save(update_fields=("joined_on_holiday",))
A post_save
signal in Django looks like this: Django 中的
post_save
信号如下所示:
from django.dispatch import receiver
@receiver(models.signals.post_save, sender=User)
def your_function(sender, instance, using, **kwargs):
# your code that you want to run
instance.save()
Be careful with saving the instance - that will itself cause the post_save
signal to run again.保存实例时要小心——这本身会导致
post_save
信号再次运行。 You should put a condition in place that will only evaluate once before the instance is saved.您应该设置一个在保存实例之前只评估一次的条件。 Something like:
就像是:
if instance.joined_on_holiday == False:
instance.joined_on_holiday = True
instance.save()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.