4

I have two tables:

class Advertisement(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    author_email = models.EmailField()

class Verification(models.Model):
    advertisement = models.ForeignKeyField(Advertisement)
    key = models.CharField(max_length=32)

And I need to auto populate Verification table after adding new advertisement.

def gen_key(sender, instance, created, **kwargs):
    if created:
        from hashlib import md5
        vkey = md5("%s%s" % (instance.author_email, instance.created_at))
        ver = Verification(advertisement=instance)
        ver.key = vkey
        ver.save()

post_save.connect(gen_key, sender=Advertisement)

Of course it doesn't work. Django 1.2 Q: How should I do it?


Ok, halfly solved.
The problem is that post_save() for parent model doesn't calling for childs models.
So you can solve it by providing child class directly.

class Advertisement(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    author_email = models.EmailField()

class Sale(Advertisement):
    rooms = models.IntegerField(max_length=1)
    subway = models.ForeignKey(Subway)

class Verification(models.Model):
    advertisement = models.ForeignKeyField(Advertisement)
    key = models.CharField(max_length=32)

def gen_key(sender, instance, created, **kwargs):
    code goes here
post_save.connect(gen_key, sender=Sale, dispatch_uid="my_unique_identifier")

So next question is "How can I use parent class for post_save()?"

Bohemian
  • 412,405
  • 93
  • 575
  • 722
mktums
  • 426
  • 1
  • 4
  • 15

1 Answers1

5

instead of connecting to a specific sender, just connect to post_save in general and check the class of the saved instance in your handler eg

def gen_key(sender, **kwargs):
    if issubclass(sender, Advertisement):
        code goes here
post_save.connect(gen_key, dispatch_uid="my_unique_identifier")
Anentropic
  • 32,188
  • 12
  • 99
  • 147
  • This worked for me but it still confuses me that I cannot specify the sender on the connect `post_save.connect(gen_key, sender='MyClass', dispatch_uid="my_unique_identifier")` – toto_tico Apr 12 '13 at 19:43
  • you can do that, my answer only makes sense in relation to @mkturns follow-up question below, where the intention is to connect for both a parent class and sub-classes. The `connect` method only does an `isinstance` type of check so in that case you want to connect with no sender and do the `issubclass` check in your own signal handler – Anentropic Apr 13 '13 at 23:47
  • Thanks for pointing that out. I was reading `issubclass` as `isinstance`. My bad. It makes sense now. – toto_tico Apr 14 '13 at 15:28