Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A create_or_get method in Django

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?

like image 880
Mridang Agarwalla Avatar asked Nov 15 '25 17:11

Mridang Agarwalla


1 Answers

There is already get_or_create, to be used like:

obj, created = MyModel.objects.get_or_create(keywordArguments)
like image 66
AndiDog Avatar answered Nov 17 '25 07:11

AndiDog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!