I read about django signals (http://docs.djangoproject.com/en/dev/topics/signals/), but as far as I understand, signals are never converted into literal SQL triggers (http://en.wikipedia.org/wiki/Database_trigger).
If I'm correct that signals and triggers are different, then which one is better and in what ways? What's the best practice?
....................
Here's a concrete example if you want one:
class Location(models.Model):
name = models.CharField(max_length=30)
class Person(models.Model):
location = models.ForeignKey('Location')
class Team(models.Model):
locations = models.ManyToManyField('Location')
I want a person to be able to join a team if and only if that person's location is within that team's set of locations. I do not know how to do that with normal relational constraints, so as far as I know I'm forced to use triggers or signals. My gut says that I should use triggers but I want to know best practice.
Django includes a “signal dispatcher” which helps decoupled applications get notified when actions occur elsewhere in the framework. In a nutshell, signals allow certain senders to notify a set of receivers that some action has taken place.
Django Triggers is a light-weight framework for having one part of an application generate a trigger while another part responds to to it. Triggers are persistent and can be scheduled to be processed at a later time.
There are 3 types of signal. pre_save/post_save: This signal works before/after the method save(). pre_delete/post_delete: This signal works before after delete a model's instance (method delete()) this signal is thrown. pre_init/post_init: This signal is thrown before/after instantiating a model (__init__() method).
First, to dispel a misconception about signals, they are not executed asynchronously. There is no background thread or worker to execute them. Like most of Django, they are fully "synchronous".
Neither. The best tool for this job is model validation - you can write your custom validation rule there and it will be enforced in the admin and your own apps.
Django signals are awesome (validation is awesome too, but sometimes you need to change something before save…). If you are working with database ONLY thru Django, it's really good idea to keep all logic in same place, imho.
Here is an example, how it works:
class Example(models.Model):
''' Example of Model (I hate foo-bars!) '''
age = models.IntegerField()
can_buy_beer = models.BooleanField(default=False)
def set_can_buy_beer(sender, instance, **kwargs):
''' Trigger body '''
if instance.age >= 21:
instance.can_buy_beer = True
else:
instance.can_buy_beer = False
# ↓ Magic — now, field Example.can_buy_beer will be autocalculated on each save!
pre_save.connect(set_can_buy_beer, sender=Example)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With