Django: Query by pk of all models
I need to query across multiple tables by primary_keys, which are unique (uuids).
My idea was to use model inheritance for querying all models at once. I've got a BaseItem and all other models are subclasses of this BaseItem model.
Now, my query does not return what I expected and needed. Here's a sample model:
from django.db import models
from django.contrib.auth.models import User
class BaseRev(models.Model):
rev_id = models.CharField(max_length=32, primary_key=True)
item_id = models.CharField(max_length=32, blank=True, null=True)
creation_date = models.DateTimeField()
class NamedRev(BaseRev):
name = models.CharField(max_length=64, blank=True, null=True)
description = models.CharField(max_length=256, blank=True, null=True)
creator = models.ForeignKey('UserProfile', related_name='namedrev_creator', blank=True, null=True)
When I create a NamedRev with pk = "1234" and make a query like
BaseRev.objects.get(pk="1234")
I get a result with the correct pk, but it's of type BaseItem. According to the docs that's the correct behaviour, as the the rev_id field does only exist in the BaseRev table开发者_C百科 and the addional fields for the NamedRev in the NamedRev table.
How do I get "proper" and complete (with all fields) objects of type NamedRev for the given query?
Cheers,
Jan
What if you set your parent class to be abstract:
class BaseRev(models.Model):
rev_id = models.CharField(max_length=32, primary_key=True)
item_id = models.CharField(max_length=32, blank=True, null=True)
creation_date = models.DateTimeField()
class Meta:
abstract = True
After you have fetched your BaseRev, do:
>>> base_rev = BaseRev.objects.get(pk="1234")
>>> base_rev.namedrev
<NamedRev: NamedRev object>
Assign the above to another variable and you should be able to access NamedRev's fields.
you could insert "type" field in your base model, so you can query the base model and then ask for it's type. override save()
method of each model to set the type before saving.
精彩评论