14π
I believe post_save fires after the save occurs, but before the transaction is commited to the database. By default, Django only commits changes to the database after the request has been completed.
Two possible solutions to your problem:
- Manage your transactions manually, and fire a custom signal after you commit.
- Have your second process wait a little while for the request to go through.
To be honest though, your whole setup seems a little bit nasty. You should probably look into Celery for asynchronous task queuing.
17π
We ran into a similar issue and we ended up using on_commit callback (NOTE: This is only possible with Django >= 1.9). So, you could possible do something like:
from django.db import transaction
class A(models.Model):
stuff...
def trigger_on_post_save( sender, instance, create, raw, **keywords):
def on_commit():
urlopen(r'http://127.0.0.1:[port]' +
reverse(some_view_url, args(instance_pk) ).read()
transaction.on_commit(on_commit)
post_save.connect( trigger_on_post_save, A )
The idea here is that you wil be calling your endpoint after the transaction has been committed, so the instance involved in the transaction will be already saved ;).
- How to restrict Django Rest Framework browsable API interface to admin users
- How do I get the django HttpRequest from a django rest framework Request?
- How can I test if my redis cache is working?
- Method in Django to display all attributes' values belonging to a created object?
7π
Itβs nice place to use decorators. There is slightly extended version of yoanis-gilβs answer:
from django.db import transaction
from django.db.models.signals import post_save
def on_transaction_commit(func):
def inner(*args, **kwargs):
transaction.on_commit(lambda: func(*args, **kwargs))
return inner
@receiver(post_save, sender=A)
@on_transaction_commit
def trigger_on_post_save(sender, **kwargs):
# Do things here
- What is the best IDE setup for web development?
- How do I write a single-file Django application?
- Create multiple objects without multiple hits to the db in Django 1.8
- Add context to every Django Admin page
1π
Had same issue when creating new model from django admin. Overriding ModelAdmin.save_model
method to manage transaction manually worked.
def save_model(self, request, obj, form, change):
from django.db import transaction
with transaction.commit_on_success():
super(ModelAdmin, self).save_model(request, obj, form, change)
# write your code here
- How to add some extra fields to the page in django-cms? (in django admin panel)
- Django unique together constraint failure?
- Django: Possible to load fixtures with date fields based on the current date?