0

I would like to get a variable in my meta class

    class Meta:
        abstract = True
        db_table = 'bikes_table'
        managed = False

I want to get a variable from self like above :

    class Meta:
        abstract = True
        db_table = 'bikes_table' if self.customers=True else 'cars_table'
        managed = False

Is it possible de get variable ? Thank you

3
  • Meta doesn't have access to self. It really is only for defining metadata for the model. So I don't think this is possible.
    – michjnich
    Commented Oct 21, 2020 at 22:07
  • "self" does not exist at class declaration time - only when the views are called.
    – jsbueno
    Commented Oct 21, 2020 at 22:08
  • 1
    I think what you want is a base model definition which you can then inherit for your cars and bikes model ...
    – michjnich
    Commented Oct 21, 2020 at 22:09

1 Answer 1

0

As stated in the comments, the surface problem is that "self" won't be available at class definition time, of course.

Some of the fields in the Metadata could have values that could change at runtime, for each instance, those will accept callback functions instead of static values (but looking at the documentation, there seems to be none)

Now, the table corresponding to a certain Model is used by the ORM and will be bound at the class level. Doubly so because a lot of the queries dealing with a class have to issue database statements without having an instance, as is the case for any query. I mean, in your example, a vehicle.objects.all() would have to query both database tables and bring the results together in the same response.

It could be done by subclassing Django's internal Queryset databases, and carefully rewriting it to look at the "table" model meta data in a custom way, but it would be prone to error.

So, you'd rather rethink your design. It is easier to simply have a Vehicle base class, just use "Vehicle" on your forms and relations, and derive the Bicycle and Car classes from that - either a car or a bicycle could be used wherever a vehicle can. Django provides support for the relationship itself with Generic Relations

Not the answer you're looking for? Browse other questions tagged or ask your own question.