Blog of science and life

Contact
Archives
Feed

Django Signal + Celery


Nếu bạn muốn dùng Celery task trong các Signals của Django, bạn cần làm như sau để tránh tình trạng bắn task quá nhanh, khiến bên trong task nếu query pk=id sẽ bị lỗi NotFound (do dữ liệu chưa kịp lưu vào database).

from django.db import transaction
from .models import MyModel
from .tasks import task

@receiver(post_save, sender=MyModel)
def my_model_post_save(sender, instance, **kwargs):
    transaction.on_commit(lambda: task.delay(args=(instance.id,)))

Ở đây ta đợi transaction commit xong mới chạy task. Problem solved.

Read more

Django full text search (Postgres)


Let's say we have a large database, few milions row, one-to-many relationship models with some text field, and we want to search some keywords.

Traditional way will be real pain and slow, I know. So let's do something smart and enjoy lightning-fast execution with Full Text Search.


Suppose we have an app named main and it's models look like this

from django.db import models

class Parent(models.Model):
   title = models.CharField(max_length=255)

class Child(models.Model):
   parent = models.ForeignKey(Parent, on_delete=models.CASCADE, related_name="children")
   content = models.TextField(null=True, blank=True)

For example, we want to search keyword in childs content, and we want to do it quick! You can do like this, but that not quick enough for me. Maybe because I have too damn much data. But there are other way. First we need to add this line to settings.py

settings = [
    # ...
    "django.contrib.postgres …
Read more