![](/img/trans.png)
[英]How to get inline model in post_save instance (Django Signals)?
[英]How can I implement post_save signals in Django?
我目前正在構建一個地理定位應用程序,但我有點卡在某個地方。 我正在嘗試在此代碼中實現 post_save Django 信號,但我無法弄清楚我到底需要做什么。 這里的任何幫助將不勝感激。 這是我的代碼:
from ipaddress import ip_address
從 django.contrib.auth 導入 get_user_model
從 celery 導入 shared_task 從 apps.users.abstractapi 導入 AbstractAPI
用戶 = get_user_model()
@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",))
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()
保存實例時要小心——這本身會導致post_save
信號再次運行。 您應該設置一個在保存實例之前只評估一次的條件。 就像是:
if instance.joined_on_holiday == False:
instance.joined_on_holiday = True
instance.save()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.