0

I want to set the db_table Meta class attribute in a base class so that all inherited classes will have their names in it, similar to how Django treats related_name model field attribute:

class BaseModel(models.Model):
    class Meta:
        db_table = 'prefix_%(class)s'

So the inherited model:

class SubModel(BaseModel):
    pass

will have db table prefix_submodel.

Is that possible? Can the Meta class access the inheriting class' model name?

2
  • Have you tried it yet, and it's failing? On a quick glance, it looks like it should work... Commented Jan 25, 2011 at 13:09
  • sure. it raises TypeError: format requires a mapping during syncdb. Commented Jan 25, 2011 at 14:01

1 Answer 1

1

No. You can't do that. It is not that simple to have same table to store for multiple classes.

What you need is probably djeneralize project.

From the examples:

class Fruit(BaseGeneralizedModel):
   name = models.CharField(max_length=30)

   def __unicode__(self):
       return self.name

class Apple(Fruit):
   radius = models.IntegerField()

   class Meta:
       specialization = 'apple'

class Banana(Fruit):
   curvature = models.DecimalField(max_digits=3, decimal_places=2)

   class Meta:
       specialization = 'banana'

class Clementine(Fruit):
   pips = models.BooleanField(default=True)

   class Meta:
       specialization = 'clementine'

which then allows the following queries to be executed:

>>> Fruit.objects.all() # what we've got at the moment
[<Fruit: Rosy apple>, <Fruit: Bendy banana>, <Fruit: Sweet
clementine>]
>>> Fruit.specializations.all() # the new stuff!
[<Apple: Rosy apple>, <Banana: Bendy banana>, <Clementine: Sweet
clementine>]
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, what djeneralize does is impressive. imo, it should be in the core of django. but what i want is to simply set a prefix for the table names that are inherited from the same model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.