tags:

views:

52

answers:

1

Suppose I have the following models:

class User(models.Model):
    pass

class A(models.Model):
    user = models.ForeignKey(User)

class B(models.Model):
    a = models.ForeignKey(A)

That is, each user owns some objects of type A, and also some of type B. Now, I'm writing a generic interface that will allow the user to view any objects that it owns. In a view, of course I can't say something like "objects = model.objects.filter(user=user)", since B has no attribute 'user'. What's the best approach to take here?

A: 

The way I would do it is to simply go through the object 'a' on class B. So in the view, I would do:

objects = B.objects.get(user=a.user)
objects += A.objects.get(user=user)

The reason I would do it this way is because these are essentially two database queries, one to retrieve a bunch of object A's and one to retrieve a bunch of object B's. I'm not certain it's possible in Django to retrieve a list of both, simply because of the way database inheritance works.

You could use model inheritance as well. This would be making a base class for both objects A and B that contains the common fields and then retrieving a list of the base classes, then convert to their proper types.

Edit: In response to your comment, I suggest then making a base class that contains this line:

user = models.ForeignKey(User)

Class A and B can then inherit from that base class, and you can thus now just get all of the objects from that class. Say your base class was called 'C':

objects = C.objects.get(user=user)

That will obtain all of the C's, and you can then figure out their specific types by going through each object in objects and determining their type:

for object in objects:
    if object.A:
        #code
    if object.B:
        #code
AlbertoPL
I need this to be generic, so that the view doesn't directly know that B contains an object of type A. It just needs to be given a model name and a user, and produce a list of objects that the user owns.
Mike J
See my edit in my post above.
AlbertoPL
Thanks, I think that will work. I guess I just feel like I'm polluting the object model somehow, since conceptually each object doesn't really need to have a 'user' attribute, as it could be deduced without it.
Mike J
Yes, I think consider that as well. I guess this is just a trade-off you will have to justify for yourself. Good luck!
AlbertoPL