Why does Django use `Meta` inner class in models? - python

If I want to describe some information such as ordering, if the model is proxy or abstract, which fields must be unique together, then I need to put this information in class named Meta that is inside of my model class. But if I want to change the manager I put information about it in the model class itself.
class Product(models.Model):
class Meta:
unique_together = ...
ordering = ...
objects = My manager()
Why did Django developers made such design decision (forcing to put some information about the model in the Meta inner class instead of the model class itself)? Why wouldn't they just let me put "ordering", "uniwue_tpgether" in the model class itself?
EDIT: Anentropic commented about it being a kind of namespacing. I thought about it while creating the question. If Meta inner class is a way of namespacing metainformation about the model so I'm free to create fields in the model class itself then why wasn't objects attribute put in the Meta class? There are many more attributes (save, refresh_from_db, get_deffered_fields, and more) that exist in the model class itself rather than in the Meta class that can collide with my field names if I dont know about them.

It's probably to avoid conflicts with field names. For example, by putting ordering into the Meta class, you are still free to have a field named ordering on your model.
But then, why is the manager, named objects in the example, not in Meta as well? The reason is probably that you can access it as Product.objects, which is unlike any other Meta field. Moreover, the manager can have a custom name, for example Product.products.
You mentioned that there might also be conflicts with other class attributes besides meta fields, like methods. This is true, as mentioned in the documentation:
Be careful not to choose field names that conflict with the models API like clean, save, or delete.
The risk of a conflict is quite small here, because methods usually have a verb in their name, like save or get, whereas field names are typically nouns, like name, id or price.

Related

What is exactly Meta in Django?

I want know simply what is Meta class in Django and what they do.
from django.db import models
Class Author(models.Model):
first_name=models.CharField(max_length=20)
last_name=models.CharField(max_length=20)
class Meta:
ordering=['last_name','first_name']
Meta is a word that originates from the ancient Greeks and it means "meta is used to describe something that's self-reflective or self-referencing.". Specific to Django it is a class in which you describe certain aspects of your model. For example how the records should be ordered by default, what the name of the database table for that model is, etc.
The documentation on meta options [Django-doc] says:
Model metadata is "anything that’s not a field", such as ordering options (ordering), database table name (db_table), or human-readable singular and plural names (verbose_name and verbose_name_plural). None are required, and adding class Meta to a model is completely optional.
The Django documentation contains an exhaustive list of Django's model Meta options. For example for the ordering attribute [Django-doc]:
The default ordering for the object, for use when obtaining lists of objects. (...)
Here the ordering specifies that if you query for Author objects, like Author.objects.all(), then Django will, if you do not specify any ordering, order the Authors by last_name first, and in case of a tie, order by first_name.
You are asking a question about two different things:
Meta inner class in Django models:
This is just a class container with some options (metadata) attached to the model. It defines such things as available permissions, associated database table name, whether the model is abstract or not, singular and plural versions of the name etc.
Short explanation is here: Django docs: Models: Meta options
List of available meta options is here: Django docs: Model Meta options
Copied from here, consider liking:
How does Django's Meta class work?
Read this for further understanding

Django REST framework serializing model combinations

I'm programming an online game with a JavaScript client and I use Django REST framework for the backend. I have written a quest system for it.
My quests objects are dynamically created from a django model QuestTemplate which stores information like the Quest desription and the titel (the part that is the same for every user); and another model QuestHistory where I put the information about the state of quest for a certain user: so it has fields like user and completed. They also have some nested objects: Tasks and, Rewards which are created in a similar way to the the Quest objects.
I added a pure python class Quest that combines all the fields of those models, and then I wrote a Serializer for this class. The drawback is that I have to define all the fields again in the QuestSerializer
I have seen that for the ModelSerializer you can use a inner class Meta where you specifiy the model and . Is there also a way to do this with a normal python class instead of a model (with my Quest class).
http://www.django-rest-framework.org/api-guide/serializers#specifying-nested-serialization
Or:
Is it possible to specify more than one model in this inner class, so that it takes fields from my model QuestTemplate and some other fields from my model QuestHistory?
(I'm also not sure about whether this structure makes sense and asked about it here: django models and OOP design )
In the class Meta of the ModelSerializer you can specify only one Model as far as I know. However there are possibilities to add custom fields to the serializer. In your case you could maybe try with:
custom_field = serializers.SerializerMethodField('some_method_in_your_serializer')
You should add the method to your serializer like this:
def some_method_in_your_serializer(self, obj):
# here comes your logic to get fields from other models, probably some query
return some_value # this is the value that comes into your custom_field
And add the custom_field to fields in the class Meta:
class Meta:
fields = ('custom_field', 'all_other_fields_you_need')
Take a look in the documentation about SerializerMethodField for deeper understanding.

Django Application: Foreign Key pointing to an abstract class

I am trying to design a framework to help implement complex web flows. The framework would provide with abstract classes which could inherited and implemented by the sub-apps. Now, as you can see my abstract class Action has a Foreign Key with Stage. Since, it has a foreignkey it could not be made abstract due to which it would have its own table. So, If I have 2 implementing application then my first application can see all the Stages for itself as well as for the other application. I could make some tweaks in the queries to avoid this. But I want to know if there is solution so, that my implementing Action class could directly point to the Inheriting Stage class.
parent_app/models.py
class Stage(models.Model):
name = models.CharField(max_length=255)
class Action(models.Model):
stage = models.ForeignKey(Stage)
class Meta:
abstract = True
sub_app1/models.py
class StageImpl1(Stage):
pass
class ActionImpl1(Action):
...
sub_app2/models.py
class StageImpl2(Stage):
pass
class ActionImpl2(Action):
...
Update:
The current situation is:
ActionImpl1 has a foreignkey to Stage
What I would to have is:
ActionImpl1 to have a foreignkey with StageImpl1
An abstract class is a class that doesn't exist. It is used as a basis for other classes. It is never never ever initialized.
Something that does not exist cannot have a foreign key pointing at it!
Something to look at, if you want to have a way to point at several different kinds of classes: generic relations. This is Django's build-in way to have something that looks like a foreign key point at a number of different objects.
It is imposible.
Think what would happen to all the classes with a foreign key pointing A if A is abtract and several classes inherit from A.
I dont know your requirements but I maybe you should consider using multitable inheritance, and point the FK to the parent table.
From the Django documentation:
Multi-table inheritance
https://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance
The second type of model inheritance supported by Django is when each
model in the hierarchy is a model all by itself. Each model
corresponds to its own database table and can be queried and created
individually. The inheritance relationship introduces links between
the child model and each of its parents (via an automatically-created
OneToOneField). For example:

Django: composite fields or embedded classes (like JPA)?

Suppose you have to model several classes that should have composite properties like dimensions (width and height) or phone number (prefix, number and extension).
In Java (using JPA 2) I'd create a Dimensions class and annotate it with #Embeddable. This causes Dimension's fields (e.g. width and height) to be embedded into every class that declares a property of type Dimensions.
How do you model these with Django while avoiding code duplication? It doesn't make sense to create a separate Dimensions model and reference it with a ForeignKey field. And the classes do not have enough in common to justify model inheritance.
I think you might be over-thinking inheritance. Inheritance is and is actually the recommended method to composite models. The following is an example of how properly use model inheritance in Django:
class PhoneModelBase(model.Model):
phone = models.CharField(max_length=16)
...
class Meta:
abstract = True
class PhoneModel(PhoneModelBase):
# phone is here without typing it
# the only restriction is that you cannot redefine phone here
# its a Django restriction, not Python restriction
# phone = models.CharField(max_length=12) # <= This will raise exception
pass
So what this does is it creates a model PhoneModelBase, however the key here is that it uses class Meta with abstract=True.
Here is more of behind the scenes of what is going on and some explanation of some of the Python concepts. I assume that you are not aware of them since you mentioned Java in the question. These Python concepts are actually rather confusing concepts so my explanation is probably not full, or even confusing, so if you will not follow, don't mind. All you have to know is to use abstact = True. Here is the official doc: https://docs.djangoproject.com/en/dev/topics/db/models/#abstract-base-classes.
Meta attribute within PhoneModelBase is just that, an attribute. It is the same as any other attribute within the class, except its a class instance (remember that in Python classes and functions are first order members). In addition, Python has this thing called __metaclass__ which you can add to you classes. __metaclass__ defines a way of how an instance of a class is build. More about that here. Django uses these in how it creates model class instances.
So to create the PhoneModelBase class, the following is a rough outline:
When an instance of the PhoneModelBase class (the class itself, not instance of class - PhoneModelBase()) is being created, the __metaclass__ which comes from model.Model due to inheritance takes over the creation process
Within the __metaclass__, Python calls the function which creates the actual class instance and passes to it all of the fields from the class you are trying to create - PhoneModelBase. That will include phone, Meta and any other fields you define
It sees the Meta attribute and then it starts analyzing its attributes. According to the values of these attributes, Django will change the behavior of the model
It sees the abstract attribute and then changes the logic of the class its trying to create - PhoneModelBase by not storing it in db
So then the PhoneModelBase, even though its definition looks very similar to a regular model, its not a regular model. It is just an abstract class which is meant to be used as composite in other models.
When other models inherit from PhoneModelBase, their __metaclass__ will copy the attributes from the base model as if you manually typed those attributes. It will not be a foreign key on anything like that. All of the inherited attributes are going to be a part of the model and will be in the same table.
Hopefully all of this makes some sense. If not, all you have to remember is just to use Meta class with abstract = True.
EDIT
As suggested in the comment, you can also inherit from multiple base classes. So you can have PhoneModelBase, DimensionsModelBase, and then you can inherit from both of these (or more), and all of the attributes from all base classes will be present in your model.

Django model class inheritance - default fields and overrides

I'm attempting to have inherited class templates, so that all my models have certain default fields, and all have default overrides for a few functions like save_model()
If I do it like this, I get the overrides, but then have to go and manually set meta data like db_table...
class ModelExtension(models.Model):
altered_by = models.CharField(max_length=64)
class SomeModel(ModelExtension):
class Meta:
db_table = 'app_somemodel'
fields = models.CharField()
...
Is there a way to get this kind of inheritance working right? So far I either have to do extra work to compensate for the drawbacks of this approach, or I'm plagued by MRO errors.2
What's an MRO error? Have you read the django docs on model inheritance? You can either have Abstract Base Classes, Multi-table inheritance, or proxy models.
http://docs.djangoproject.com/en/stable/topics/db/models/#abstract-base-classes
What you've done there is a multi-table inheritance - there's a hidden OneToOneField connecting your two models. I don't know why you think you need the db_table specified - it shouldn't be.
If you are never going to have objects of bare class ModelExtension then you want abstract base classes. In this case you put abstract=True in the Meta section, and then all the fields from the base class are added to the table for the child class. The docs explain it better than I can here.
I often find myself starting to do it one way and then flipping back and forth several times as I think more about my database structure....
If you just want to add new functionality to a model without changing its fields, use a proxy model!

Categories

Resources