python - In Django how to return an existing model instance when saving to database -


how return instance before saving database?

below similar trying accomplish:

class personne(models.model):     nom = models.charfield(max_length=100, verbose_name="origem")      def save(self, *args, **kwargs):         found = none         try:             found = personne.objects.get(nom=self.nom)             super(personne, self).save(*args, **kwargs)         except audiofile.doesnotexist:             return found   def test_personne_is_the_same(self):     p1 = personne.objects.create(nom="malcom x")     p2 = personne.objects.create(nom="malcom x")     self.assertequal(p1, p2) 

assertion giving: p1 != none

there number of reasons why save() method won't work written. (for one, return value of save() isn't used, return found has no effect.)

but there's no reason try , reinvent yourself: rid of custom save() , use get_or_create():

def test_personne_is_the_same(self):     p1, _ = personne.objects.get_or_create(nom="malcom x")     p2, _ = personne.objects.get_or_create(nom="malcom x")     self.assertequal(p1, p2) 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

IIS->Tomcat Redirect: multiple worker with default -