Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting Meta Class in Django Models

Tags:

python

django

I have a question as newbie and I am looking for the concept related to inheritance of Meta class in Django classes. Following are the models and I would appreciate if someone can help me.

class Base(models.Model):
    code = AutoSlugField(_("Slug"), max_length=128, unique=True,
                         populate_from='name')
    name = models.CharField(_("Name"), max_length=128, unique=True)
    description = models.TextField(_("Description"), blank=True)
    countries = models.ManyToManyField('Country',
                                       blank=True, verbose_name=_("Countries"))
    is_discounted = False
    class Meta:
        app_label = 'shipping'
        ordering = ['name']
        verbose_name = _("Shipping Method")
        verbose_name_plural = _("Shipping Methods")


class OrderAndItemCharges(Base):
    price_per_order = models.DecimalField(
        _("Price per order"), decimal_places=2, max_digits=12,
        default=D('0.00'))
    price_per_item = models.DecimalField(
        _("Price per item"), decimal_places=2, max_digits=12,
        default=D('0.00'))
    free_shipping_threshold = models.DecimalField(
        _("Free Shipping"), decimal_places=2, max_digits=12, blank=True,
        null=True)
    class Meta(Base.Meta):
        app_label = 'shipping'
        verbose_name = _("Order and Item Charge")
        verbose_name_plural = _("Order and Item Charges")

Traceback:

    class OrderAndItemCharges(Base):
  File "C:\Users\AliKhan\supermarekt\market\shipping\models.py", line 46, in Or
derAndItemCharges
    class Meta(Base.Meta):
AttributeError: type object 'Base' has no attribute 'Meta'

I've changed the class import behavior to get over with like following. That might be causing the issue. Reason is that I need to ease the code for dashboard application for the shop. So I imported default Django source for importing Django classes and changed it like below:

from django.apps.config import MODELS_MODULE_NAME
def get_class(module_label, classname):
    return get_classes(module_label, [classname])[0]
def get_classes(module_label, classnames):
    if not module_label:
        raise ValueError(
            "Module Does Not Exists")

    market_module_label = "%s" % (module_label)
    market_module = _import_module(market_module_label, classnames)
    return _pluck_classes([market_module], classnames)
def _import_module(module_label, classnames):
    try:
        return __import__(module_label, fromlist=classnames)
    except ImportError:
        __, __, exc_traceback = sys.exc_info()
        frames = traceback.extract_tb(exc_traceback)
        if len(frames) > 1:
            raise

Filename is loading.py and I learned it from Django-Oscar. However I made slight changes to tailor it for my need. So might be the issue lie here. Please assist

like image 793
Ali khan Avatar asked Dec 31 '16 14:12

Ali khan


People also ask

How do I inherit a class in Django?

Multi-table inheritance: Use this when the parent class has common fields, but the parent class table also exists in the database all by itself. Proxy models: Use this when you want to modify the behavior of the parent class, like by changing orderby or a new model manager.

What does class Meta do in Django models?

Model Meta is basically the inner class of your model class. Model Meta is basically used to change the behavior of your model fields like changing order options,verbose_name, and a lot of other options. It's completely optional to add a Meta class to your model.

What is your understanding of Django model inheritance?

Proxy Model Inheritance: You Inherit from base class and you can add your own properties except fields. base class should not be abstract class. we can not use multiple inheritance in proxy models. The main use of this is to overwrite the main functionalities of existing model.

What is the use of meta class in Django?

The Meta class can be used to define various things about the model such as the permissions, database name, singular and plural names, abstraction, ordering, and etc. Adding Meta classes to Django models is entirely optional. This class also comes with many options you can configure.

What are the methods of inheritance in Django?

There are three styles of inheritance possible in Django. Abstract base classes: Use this when the parent class contains common fields and the parent class table is not desirable. Multi-table inheritance: Use this when the parent class has common fields, but the parent class table also exists in the database all by itself.

Can a child class override a model field in Django?

In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this isn’t usually permitted for model fields.

What is a model in Django?

A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table. Each model is a Python class that subclasses django.db.models.Model. Each attribute of the model represents a database field.


1 Answers

You should declare your Base class abstract in order to access its Meta class as an attribute.

class A(models.Model):
    class Meta:
        app_label='yourapp'
        abstract=True

class B(A):
    class Meta(A.Meta):
        db_table='yourtable'

Relevant documentation: https://docs.djangoproject.com/en/3.2/topics/db/models/#meta-inheritance

like image 167
M1L0U Avatar answered Sep 18 '22 14:09

M1L0U