2

Here are two of my models in Django(1.5):

class ActNews(models.Model):
    actNews_Activity_key = ForeignKey(Activity)
    actNewsCheck = BooleanField(default=False)
    … … 

    def save(self, *args, **kwargs):
        if self.actNewsCheck == True:
            self.actNews_Activity_key.act_newsPostCheck = True
            self.actNews_Activity_key.save()
        super(ActNews, self).save(*args, **kwargs)

class Activity(models.Model):
    act_newsPostCheck = BooleanField(default=False)
    … …

What I want to do is when ActNews.actNewsCheck is True, then set act_newsPostCheck to True automatically. I override the save() method in ActNews.

Am I doing it correctly? I mean, reasonably? Should I use signal instead of this? BTW, I'm new to Django's signal, and I'm really confused about it, and I seem to fail to see a full example while searching around, it would be really great if you can provide one!

Any ideas? Thanks in advance!

ray6080
  • 873
  • 2
  • 10
  • 25
  • 1
    I have tried to explain `signals` v/s `save` here. Hope it helps: http://stackoverflow.com/questions/17645801/when-to-use-pre-save-save-post-save-in-django/17658156#17658156 – karthikr Mar 13 '14 at 01:47
  • 7
    Rule of thumb: If action on one model's instance affects another model, signals are the cleanest way to go about. This is an example where you can go with a signal, because you might want to avoid `activity.save()` call from within the `save()` method of `class ActNews` – karthikr Mar 13 '14 at 01:48
  • @karthikr Yeah, but can you show me a full example using pre_save() ? Should I define a @reveiver and register a signal using `dispatch`? and What else? Thanks! – ray6080 Mar 13 '14 at 02:10
  • http://stackoverflow.com/questions/17257910/cant-get-post-save-to-work-in-django/17259611#17259611 – karthikr Mar 13 '14 at 02:19
  • Can I put the `@receiver` into my model? I mean, like my model `ActNews` send a signal indicating that it's going to saved, and `Activity` receives it and modifies its `act_newsPostCheck` to be `True`. I can quite understand the theory, but I don't know how to modify my `Activity` model once receives the `pre_save()` signal in my example. Thanks!! – ray6080 Mar 13 '14 at 02:37
  • dont use pre_save. use post_save. There are lots and lots and lots of examples availalbe on SO, and Google. – karthikr Mar 13 '14 at 02:41
  • Does this answer your question? [Django signals vs. overriding save method](https://stackoverflow.com/questions/170337/django-signals-vs-overriding-save-method) – Flimm Dec 04 '19 at 13:23
  • Does this answer your question? [Django: When to customize save vs using post-save signal](https://stackoverflow.com/questions/5597378/django-when-to-customize-save-vs-using-post-save-signal) – ldrg Jan 07 '22 at 18:40

0 Answers0