0

Python and django newbie question, here is code:

class Client(User)
   #some fields

client=Client()
client.save()

user=User.objects.all()[0]

#want to ckeck type of user, expect that it is Client:
isinstance(user,Client) #returns false

#but this works:
isinstance(user,User) #returns true

But I expect that user is Client. What's wrong?

Addition: Need to get subclass object first, and it works fine:

if hasattr(user,'client'):
        client=user.client

Addition 2: Guys, you so angry so I afraid to post anything more in this question :) It's closed, and I fully understood my absolutely vacuum in knowledge of django, python, polymorphism and other IT technologies, thanks ))

Artyom Chernetsov
  • 1,394
  • 4
  • 17
  • 34
  • 2
    You're doing it wrong. Django has a 'Group' model to allow you to distinguish different types of users. Do not subclass Django's `User` class like this. Read questions like this: http://stackoverflow.com/questions/4789021/in-django-how-do-i-check-if-a-user-is-in-a-certain-group. That's the correct approach. Delete all your code that attempts to subclass `User`. Close this question. And start again using `Group` correctly. – S.Lott Feb 09 '12 at 10:49
  • Why not to subclass User? Django allows it: https://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance. I need to extend User with custom fields, so nothing is wring with subclassing. – Artyom Chernetsov Feb 09 '12 at 11:30
  • But groups for distinguishing looks fine, I use that, thanks – Artyom Chernetsov Feb 09 '12 at 11:33
  • 1
    "need to extend User with custom fields". That's why there's a "Profile" extension to User. Read this: https://docs.djangoproject.com/en/1.3/topics/auth/#storing-additional-information-about-users. Do not subclass User. And -- in general -- subclasses don't work the way you're describing them in the question. If you think you need to use `isinstance`, you have failed to understand polymorphism. For your need, just read the Django documentation on Groups and Profiles. – S.Lott Feb 09 '12 at 13:58

2 Answers2

2

The problem is that Django's querysets aren't aware of inheritance. So when you query on User, it won't ever return the subclasses.

The easiest solution is to do something like this:

try:
    client = user.client
except Client.DoesNotExist:
    # handle exception

Of course, if you have multiple subclasses of User, this gets slightly more complicated. There are ways of getting Django to do model inheritance properly, but they're all a little bit hacky.

Andrew Ingram
  • 5,160
  • 2
  • 25
  • 37
0

your expectation is wrong. you query the User class, why do you expect to get a Client out of it?!

akonsu
  • 28,824
  • 33
  • 119
  • 194