2
To get the id
you need to try the answer provided by @JPG. But since the save()
method is being called in initial step, the urlhash might not get updated as it is not saved in the instance. To update the urlhash
, you can do something like:
def save(self):
super(Group1, self).save()
if not self.urlhash:
if self.user.profile.user_type == 'Business User':
urlhash = 'B' + str(self.User.id) + ('00') + str(self.id)
Group1.objects.filter(pk=self.pk).update(urlhash=urlhash)
else:
self.urlhash = 'P' + str(self.User.id) + ('00') + str(self.id)
Group1.objects.filter(pk=self.pk).update(urlhash=urlhash)
7
Why self.id
is None
?
This is because Django assigns the id
/pk
values after the object creation, that is after calling the save()
method of model.
So, call the save()
method and then try to do your logic, as below
def save(self):
super(Group1, self).save()
if not self.urlhash:
if self.user.profile.user_type == 'Business User':
self.urlhash = 'B' + str(self.User.id) + ('00') + str(self.id)
<b>self.__class__.objects.filter.(pk=self.pk).update(urlhash=urlhash)</b>
else:
self.urlhash = 'P' + str(self.User.id) + ('00') + str(self.id)
<b>self.__class__.objects.filter.(pk=self.pk).update(urlhash=urlhash)
UPDATE
I for got one point that the instance should be again updated after calling the the save()
method. So I had used the statement
self.__class__.objects.filter.(pk=self.pk).update(urlhash=urlhash)
Thanks to @sanip for the idea got from his answer
- [Django]-How to install mod_wsgi on Windows+XAMPP in 2017
- [Django]-How to connect Celery worker to django test database
- [Django]-Django : custom management command not registered using app config
- [Django]-Django: two sessions in the same browser
Source:stackexchange.com