I was looking if Django had some kind of create_or_get method but it seems that it doesn't have one. What I'm looking for the method to is that if the record doesn't exist, it is created but if it exits, it is returned.
I wrote one and here's what it looks like:
def create_or_get(self, url):
try:
return Host.objects.create(url = url)
except IntegrityError, e:
return Host.objects.get(url = url)
Where should I places this method, in the Model or in the Manager?
There is already get_or_create, to be used like:
obj, created = MyModel.objects.get_or_create(keywordArguments)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With