1👍
✅
There are a number of reasons why your save()
method won’t work as written. (For one, the return value of save()
isn’t used, so return found
has no effect.)
But there’s no reason to try and reinvent this yourself: get rid of your custom save()
and just 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)
1👍
Django model gives a function called get_or_create
which returns object and a flag which says created or not. i.e (obj, True or False).
So what you can do in save
is.
found, created = AudioFile.objects.get_or_create(nom=self.nom)
if created:
super(Personne, self).save(*args, **kwargs)
return found
If this doenot work you can do
try:
found = AudioFile.objects.get(nom=self.nom)
except AudioFile.DoesNotExist:
found = AudioFile(nom=self.nom)
found.save()
super(Personne, self).save(*args, **kwargs)
return found
Also shouldnot your Personne
inherit models.Model
?
UPDATE:
Basically if there is no model called AudioFile
and you are not checking relation in Personne
then next answer is sensible choice to test.
- [Answered ]-How can I insert data in two different models?
- [Answered ]-Prevent change of field if related objects exist?
- [Answered ]-CSRF verification failed in django
Source:stackexchange.com