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

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.

Related

Django: Are Django models dataclasses?

Can we say that Django models are considered dataclasses? I don't see #dataclass annotation on them or on their base class model.Models. However, we do treat them like dataclasses because they don't have constructors and we can create new objects by naming their arguments, for example MyDjangoModel(arg1= ..., arg2=...).
On the other hand, Django models also don't have init methods (constructors) or inherit from NamedTuple class.
What happens under the hood that I create new Django model objects?
A lot of the magic that happens with models, if not nearly all of it, is from its base meta class.
This can be found in django.db.models.ModelBase specifically in the __new__ function.
Regardless of an __init__ method being defined or not (which actually, it is as per Abdul's comment), doesn't mean it can or should be considered a dataclass.
As described very eloquently in this SO post by someone else;
What are data classes and how are they different from common classes?
Despite django models quite clearly and apparently seeming to have some kind of data stored in them, the models are more like an easy to use (and reuse) set of functions which leverage a database backend, which is where the real state of an object is stored, the model just gives access to it.
It's also worth noting that models don't store data, but simply retrieves it.
Take for example this simple model:
class Person(models.Model):
name = models.CharField()
And then we did something like this in a shell:
person = Person.objects.get(...)
print(person.name)
When we access the attribute, django is actually asking the database for the information and this generates a query to get the value.
The value isn't ACTUALLY stored on the model object itself.
With that in mind, inherently, django models ARE NOT dataclasses. They are plain old regular classes.
Django does not work with data classes. You can define a custom model field. But likely this will take some development work.

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

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.

Django model polymorphism without Multi-Table Inheritance and additional JOIN

I’m quite new to Django and I’m trying to implement polymorphism inside a Django model, but I can’t see how to do. Before going on I have to say I’ve already tried django-model-utils and django-polymorphism, but they don’t do exactly what I’m looking for.
I have a model called Player, each player has a Role and each Role has different behaviours (i.e. their methods return different values):
class Player(models.Model):
username=models.TextField()
role=models.ForeignKey(Role) #Role is another model with a field called ’name'
def allow_action(self)
#some stuff
class RoleA():
def allow_action(self):
#some specific stuff
class RoleB():
pass
I want that every time I retrieve any instance of Player (in example through Player.objects.filter(…)) every instances has the allow_action() method overwritten by the custom one defined inside the specific class (RoleA, RoleB, etc…) or use the default method provided in Player if the related subclass has no method called with the same name (RoleA, RoleB, etc... are the same role name stored in Player.role.name).
CONSTRAINTS:
Since subclasses (RolaA, RoleB, etc…) do not add new field but only overwrite methods all data have to be stored inside Player’s table, so I don’t want to use Django Multi-Table Inheritance but something more similar to Proxies.
I don’t want to perform additional JOIN to determine specific subclass type since all informations needed are stored inside Player’s table.
I think that this is a standard polymorphism pattern but I don’t see how to implement it in Django using the same table for all players (I've already implemented this polymorphism but not linked to a Django model). I’ve seen Django has a kind of inheritance called “Proxy” but it doesn’t allow to make queries like Player.objects.filter(…) and get instances with method overwritten by custom ones (or at least this is what I understood).
Thanks in advance.
Disclaimer: I've not used django-polymorphic, and this code is based on 5 minutes spent scanning the docs and is entirely untested but I'll interested to see if it works:
from polymorphic import PolymorphicModel
class Role(PolymorphicModel):
name = models.CharField()
class RoleA(Role):
def allow_action(self):
# Some specific stuff...
class RoleB(Role):
pass
class Player(models.Model):
username=models.TextField()
role=models.ForeignKey(Role) #Role is another model with a field called ’name'
def allow_action(self)
if callable(getattr(self.role, "allow_action", None):
self.role.allow_action()
else:
# default action...
Now I believe you should be able to create an instance of Role, RoleA, or RoleB and have Player point to it in the foreign key. Calling allow_action() on an instance of Player will check to see if the instance of Role (or RoleA, RoleB etc) has a callable attribute allow_action() and if so, it will use that, otherwise it will use the default.

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:

Using self in Django Model classes

While adding model class to models.py in Django, why don't we use self with the field variables which we define? Shouldn't not using self field variables make them class variables instead,which "may" cause a problem.
Django uses metaclasses to create the actual class based on the class definition your provide. In brief, upon instantiation of your model class, the metaclass will run through your model field definitions and return a corresponding class with the appropriate attributes.
To answer your question directly, using class variables instead of instance variables (object.self) allows the metaclass to inspect the class attributes without having to first instantiate it.
For more information, have a look at the source and the following docs:
https://code.djangoproject.com/wiki/DynamicModels
https://code.djangoproject.com/wiki/DevModelCreation

Categories

Resources