I have a class in which I want to override a method get_or_create. Basically, if my class does not save the answer, I want it to execute some kind of process in order to get the answer, and it is not provided. A method is really a method get_or_retrieve. So the class:
class P4User(models.Model):
user = models.CharField(max_length=100, primary_key=True)
fullname = models.CharField(max_length=256)
email = models.EmailField()
access = models.DateField(auto_now_add=True)
update = models.DateField(auto_now_add=True)
@classmethod
def get_or_retrieve(self, username, auto_now_add=False):
try:
return self.get(user=username), False
except self.model.DoesNotExist:
import P4
import datetime
from django.db import connection, transaction, IntegrityError
p4 = P4.P4().connect()
kwargs = p4.run(("user", "-o", username))[0]
p4.disconnect()
params = dict( [(k.lower(),v) for k, v in kwargs.items()])
obj = self.model(**params)
sid = transaction.savepoint()
obj.save(force_insert=True)
transaction.savepoint_commit(sid)
return obj, True
except IntegrityError, e:
transaction.savepoint_rollback(sid)
try:
return self.get(**kwargs), False
except self.model.DoesNotExist:
raise e
def __unicode__(self):
return str(self.user)
Now I fully admit that I used db / models / query.py as a starting point. My problem is on this line.
obj = self.model(**params)
I can get the parameters, but I have not defined self.model. I do not understand what it should be, and it is not intuitively obvious what value should be. Even looking back at query.py, I can't figure it out. Can someone explain this to me? I would really like to understand this and fix my code.
thanks