I am getting very strange error when I am using select_related. I have created a model which extends the auth_user table. For your reference I am pasting the model below
class BasicDetails(models.Model):
username = models.OneToOneField(User)
name = models.CharField(max_length = 100, verbose_name = "Name")
sex = models.CharField(max_length = 10, verbose_name = "Sex", choices = GENDER_CHOICES)
dob = models.DateField(verbose_name = "Date of Birth")
mothertongue = models.CharField(max_length = 20, verbose_name = "Mother Tongue", choices = LANGUAGES_CHOICES)
The above table has only one record and when I run the below query in the django shell its working fine and I am able to retrieve the values.
basicdetails = BasicDetails.objects.select_related('auth_user__username',request.user)
However when I input the same query in my views and template I am getting below error.
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111.response = callback(request, *callback_args, **callback_kwargs)
File "/home/vikramt/python/OpenMatrimony/wedding/views.py" in myprofile
160.basicdetails = BasicDetails.objects.select_related('auth_user__username',request.user)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in select_related
173.return self.get_query_set().select_related(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in select_related
686.obj.query.add_select_related(fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py" in add_select_related
1759.for part in field.split(LOOKUP_SEP):
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py" in inner
185.return func(self._wrapped, *args)
Exception Type: AttributeError at /myprofile/
Exception Value: ‘User’ object has no attribute ‘split’
Can someone help me on this context. I couldn’t able to understand what was the problem. Any clues?
-Vikram
select_relatedexpects its parameters to be strings. Yourrequest.userobject is not a string, and don’t have asplit()method. That is why an AttributeError is being raised.But the tricky part is that, as you said, when you did the same thing from inside a shell session, it worked. I would risk to say that in that shell context,
request.userwas somehow a string, or was behaving like a string.Anyway, why are you passing an User instance to select_related? I mean, what do you want to achieve by doing that?
Edit
Ok, if you want to retrieve the record of BasicDetails for the current logged
in user, you should be using the
filtermethod. It’s used tofilter a queryset:
The
select_relatedmethod is used to tell the ORM to do somethinglike a SQL join to populate the specified related columns of the results.
And I would recommend you to rename your
usernamecolumn tosomething more clear. It’s a relation to the user table, so you should call it
just
user.