custom save method on model - django

后端 未结 2 1855
后悔当初
后悔当初 2021-02-04 12:25

I am overriding the save method on one of my models:

def save(self, *args, **kwargs):
    self.set_coords()
    super(Post, self).save(*args, **kwargs)

def __un         


        
相关标签:
2条回答
  • 2021-02-04 12:47
    def save(self, *args, **kwargs):
        if not self.pk:
            self.set_coords()
        super(Post, self).save(*args, **kwargs)
    
    0 讨论(0)
  • 2021-02-04 12:51

    I think the correct way to do it is using post_save signal:

    def set_coords(sender, **kw):
        model_instance = kw["instance"]
        if kw["created"]:
            toFind = model_instance.address + ', ' + model_instance.city + ', ' + \
            model_instance.province + ', ' + model_instance.postal
            (place, location) = g.geocode(toFind)
            model_instance.lat = location[0]
            model_instance.lng = location[1]
            model_instance.save()
    post_save.connect(set_coords, sender=MyModel)
    
    0 讨论(0)
提交回复
热议问题