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.
models.py
class Obj1(models.Model)
name
prop1
prop2
prop3
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
self.name = name
self.prop1 = prop1
self.save()
return 0
elif len == 1:
# Object does exists in DB
self = objects[0] # <<< Is it possible to do like this?
return 1
else:
# Something wrong, too many objects in DB
return len
main.py
...
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"
else:
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.
Thanks!