Assignin object to self inside class method

I want to do a check inside model whether object already exists in DB or not, and if its exists to read all properties from DB and assign to same object.

class Obj1(models.Model)
    def obj_check(self, name, prop1):
        objects = Obj1.object.filter(name=name, prop1=prop1)
        len = len(objects)
        if len == 0:
            # Object does not exists in DB
   = name
            self.prop1 = prop1
            return 0
        elif len == 1:
            # Object does exists in DB
            self = objects[0]  # <<< Is it possible to do like this?
            return 1
            # Something wrong, too many objects in DB
            return len


obj = Obj1()
check = obj.obj_check(name, var)
if check == 0:
    print("Such object does NOT exists")
    print("New object created")
elif check == 1:
    print("Such object already exists")
    obj.prop3 = "New Value"
    print("Something wrong, too many objects in DB")

Is this possible/right to do like this? self = objects[0]

I know I can use try: .. except Obj1.DoesNotExist: costruction, but wanted to create Object first and make less queries to DB.


No, reassigning self doesn't really do anything. It just reassigns the local variable, it does not modify the object.

You would want to implement this kind of method as a method on the model manager instead. The default manager for an object is the .objects property, but you can also implement your own manager.

    def obj_check(self, name, prop1):
        qs = self.get_query()
        objects = qs.filter(name=name, prop1=prop1)
        n = len(objects)
        if n == 0:
            # Object does not exists in DB, create it
            obj = self.create(name=name, prop1=prop1)
            return obj, 1
            obj = objects.first()
            return obj, 0

class Obj1(models.Model):
    objects = Obj1Manager()
    # ...

# ....
obj, created = Obj1.objects.obj_check(name='foo', prop1='bar')

However, it's worth noting that this already exists as a default manager method: get_or_create.

obj, created = Obj1.objects.get_or_create(name='foo', prop1='bar')
Back to Top