Get name of abstract parent model in Django - python

Suppose I have a set of Django models that are all subclasses of an abstract Base model:
from django.db import models
class Base(models.Model):
created = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
class Derived1(Base):
name = models.CharField(max_length=32, null=False, unique=True)
whatever = models.CharField(max_length=255, null=True, blank=True)
Now I can get the Field objects for Derived1 like this:
fields=models.Derived1._meta.get_fields()
This gives me all the fields, including the inherited "created" field.
Once I have this list of fields, is there any way to see that the field "created" was inherited from Base? Does the field object have any function or property that tells me the name of the model on which "created" was defined? Specifically I'm looking for some function field.get_model_name_where_defined() so that for fields defined on Derived1, that function returns "Derived1" but for the "created" field it returns "Base". Does anything like this exist?
Just to be clear, I am not looking for a way to assert that Derived1 is derived from Base. What I am looking for is a way to check any Django model and get the unknown name of the model class that is its abstract superclass, if there is such a class.

Related

Django - Overwriting parent model's Meta

I am using the package django-polymorphic-tree inside of a Django application.
The PolymorphicMPTTModel abstract model from said package has the following Meta:
class PolymorphicMPTTModel(MPTTModel, PolymorphicModel, metaclass=PolymorphicMPTTModelBase):
"""
The base class for all nodes; a mapping of an URL to content (e.g. a HTML page, text file, blog, etc..)
"""
# ... fields
class Meta:
abstract = True
ordering = (
"tree_id",
"lft",
)
base_manager_name = "objects"
Here's a model I wrote that inherits from it:
class MyNodeModel(PolymorphicMPTTModel):
parent = PolymorphicTreeForeignKey(
"self",
blank=True,
null=True,
related_name="children",
on_delete=models.CASCADE,
)
# ... fields
class Meta:
ordering = (
"tree_id",
"-lft",
)
As you can see, I'm trying to overwrite the parent's Meta.ordering attribute.
However, if I do this inside of an instance of MyNodeModel:
print(self.Meta.ordering)
it prints:
('tree_id', 'lft')
which is the parent's value for that field. It appears as though the child class is failing to override that property. Why does this happen?

How to make my models follow DRY principles

I have a model in which I need to represent different jobs for a labor application, for example:
from django.db import models
class PostFirstJobAd(models.Model):
fist_job_ad_title = models.CharField(max_length=225)
first_job_ad_description = models.TextField()
created_at = models.DateTimeField(auto_now=True)
class PostSecondJobAd(models.Model):
second_job_ad_title = models.CharField(max_length=225)
second_job_ad_description = models.TextField()
created_at = models.DateTimeField(auto_now=True)
class PostThirdJobAd(models.Model):
third_job_ad_title = models.CharField(max_length=225)
third_job_ad_description = models.TextField()
created_at = models.DateTimeField(auto_now=True)
Instantly you can see that I'm repeating title, description and created_at, I'm just changing field's name, it's not DRY and code is starting to smell. The reason for this is because I want to register every job separately inside django admin, so I will have clear situation inside site administration.
One way to make them DRY is to use Abstract base classes but I have a problem because from the docs:
This model will then not be used to create any database table.
Instead, when it is used as a base class for other models, its fields
will be added to those of the child class.
What will be the right approach in this case, can someone help me understand this.
Using abstract base models:
class JobAd(models.Model):
title = models.CharField(max_length=225)
description = models.TextField()
created_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class PostFirstJobAd(JobAd):
pass
class PostSecondJobAd(JobAd):
pass
class PostThirdJobAd(JobAd):
pass
This would create 3 tables. The base class JobAd does not have a table in the db.
Since you appear to have 3 different models with the exact same code, you should question whether you really need 3 different models at all. Another option is to just store them all in one table, and add another field for the "other" thing.
class JobAd(models.Model):
pos = models.CharField(max_length=100, choices=['first', 'second', 'third'])
title = models.CharField(max_length=225)
description = models.TextField()
created_at = models.DateTimeField(auto_now=True)
An integer field for pos is also possible.
First off, the abstract models might be what you need here. Depending on the business requirements, you may need to think a little harder on the architecture.
If, in fact, you do need to use abstract base classes:
class BaseJob(models.Model):
title = models.CharField(max_length=255)
# etc...
class Meta:
abstract = True
def method_1(self):
# base methods that work for instance data
Once that is defined, you can implement the base class in a concrete model. A concrete model is a model that doesn't use the abstract = True metaclass property (or proxy, etc.) like so:
class Job(BaseJob):
pass
If you need additional fields you can define them like any other model field but when you run makemigrations you'll find the fields get added in the migration generated.

Django GenericForeignKey: accessor clash when 2 models have same related_name

When I syncdb, I get many errors like this:
transcription.transcription1: Accessor for field 'participant_content_type' clashes with related field 'ContentType.auxi
liary_model_as_participant'. Add a related_name argument to the definition for 'participant_content_type'.
transcription.transcription1: Reverse query name for field 'participant_content_type' clashes with related field 'Conten
tType.auxiliary_model_as_participant'. Add a related_name argument to the definition for 'participant_content_type'.
My models already have related names:
# my base class which I intend to inherit from in many places.
# Many types of AuxiliaryModel will point at participant/match objects.:
class AuxiliaryModel(models.Model):
participant_content_type = models.ForeignKey(ContentType,
editable=False,
related_name = 'auxiliary_model_as_participant')
participant_object_id = models.PositiveIntegerField(editable=False)
participant = generic.GenericForeignKey('participant_content_type',
'participant_object_id',
)
match_content_type = models.ForeignKey(ContentType,
editable=False,
related_name = 'auxiliary_model_as_match')
match_object_id = models.PositiveIntegerField(editable=False)
match = generic.GenericForeignKey('match_content_type',
'match_object_id',
)
class Meta:
abstract = True
class Transcription(AuxiliaryModel):
transcription = models.TextField(max_length=TRANSCRIPTION_MAX_LENGTH,
null=True)
class Meta:
abstract = True
class Transcription1(Transcription):
pass
class Transcription2(Transcription):
pass
class Transcription3(Transcription):
pass
The problem goes away when I comment out Transcription2 and Transcription3, so it seems like the related_names clash. Do I have to make them unique? If so, is there a way to do this without having to write boilerplate code in each child class?
From the Django docs https://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name :
If you are using the related_name attribute on a ForeignKey or ManyToManyField, you must always specify a unique reverse name for the field. This would normally cause a problem in abstract base classes, since the fields on this class are included into each of the child classes, with exactly the same values for the attributes (including related_name) each time.
To work around this problem, when you are using related_name in an abstract base class (only), part of the name should contain '%(app_label)s' and '%(class)s'.
In this case, I think this will work:
participant_content_type = models.ForeignKey(ContentType,
editable=False,
related_name = '%(app_label)s_%(class)s_as_participant')
match_content_type = models.ForeignKey(ContentType,
editable=False,
related_name = '%(app_label)s_%(class)s_model_as_match')
So, using %(app_label)_transcription2_as_participant you can access the reverse of Transcription2.participant_content_type

django abstract models versus regular inheritance

Besides the syntax, what's the difference between using a django abstract model and using plain Python inheritance with django models? Pros and cons?
UPDATE: I think my question was misunderstood and I received responses for the difference between an abstract model and a class that inherits from django.db.models.Model. I actually want to know the difference between a model class that inherits from a django abstract class (Meta: abstract = True) and a plain Python class that inherits from say, 'object' (and not models.Model).
Here is an example:
class User(object):
first_name = models.CharField(..
def get_username(self):
return self.username
class User(models.Model):
first_name = models.CharField(...
def get_username(self):
return self.username
class Meta:
abstract = True
class Employee(User):
title = models.CharField(...
I actually want to know the difference between a model class that
inherits from a django abstract class (Meta: abstract = True) and a
plain Python class that inherits from say, 'object' (and not
models.Model).
Django will only generate tables for subclasses of models.Model, so the former...
class User(models.Model):
first_name = models.CharField(max_length=255)
def get_username(self):
return self.username
class Meta:
abstract = True
class Employee(User):
title = models.CharField(max_length=255)
...will cause a single table to be generated, along the lines of...
CREATE TABLE myapp_employee
(
id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
...whereas the latter...
class User(object):
first_name = models.CharField(max_length=255)
def get_username(self):
return self.username
class Employee(User):
title = models.CharField(max_length=255)
...won't cause any tables to be generated.
You could use multiple inheritance to do something like this...
class User(object):
first_name = models.CharField(max_length=255)
def get_username(self):
return self.username
class Employee(User, models.Model):
title = models.CharField(max_length=255)
...which would create a table, but it will ignore the fields defined in the User class, so you'll end up with a table like this...
CREATE TABLE myapp_employee
(
id INT NOT NULL AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
An abstract model creates a table with the entire set of columns for each subchild, whereas using "plain" Python inheritance creates a set of linked tables (aka "multi-table inheritance"). Consider the case in which you have two models:
class Vehicle(models.Model):
num_wheels = models.PositiveIntegerField()
class Car(Vehicle):
make = models.CharField(…)
year = models.PositiveIntegerField()
If Vehicle is an abstract model, you'll have a single table:
app_car:
| id | num_wheels | make | year
However, if you use plain Python inheritance, you'll have two tables:
app_vehicle:
| id | num_wheels
app_car:
| id | vehicle_id | make | model
Where vehicle_id is a link to a row in app_vehicle that would also have the number of wheels for the car.
Now, Django will put this together nicely in object form so you can access num_wheels as an attribute on Car, but the underlying representation in the database will be different.
Update
To address your updated question, the difference between inheriting from a Django abstract class and inheriting from Python's object is that the former is treated as a database object (so tables for it are synced to the database) and it has the behavior of a Model. Inheriting from a plain Python object gives the class (and its subclasses) none of those qualities.
The main difference is how the databases tables for the models are created.
If you use inheritance without abstract = True Django will create a separate table for both the parent and the child model which hold the fields defined in each model.
If you use abstract = True for the base class Django will only create a table for the classes that inherit from the base class - no matter if the fields are defined in the base class or the inheriting class.
Pros and cons depend on the architecture of your application.
Given the following example models:
class Publishable(models.Model):
title = models.CharField(...)
date = models.DateField(....)
class Meta:
# abstract = True
class BlogEntry(Publishable):
text = models.TextField()
class Image(Publishable):
image = models.ImageField(...)
If the Publishable class is not abstract Django will create a table for publishables with the columns title and date and separate tables for BlogEntry and Image. The advantage of this solution would be that you are able to query across all publishables for fields defined in the base model, no matter if they are blog entries or images. But therefore Django will have to do joins if you e.g. do queries for images...
If making Publishable abstract = True Django will not create a table for Publishable, but only for blog entries and images, containing all fields (also the inherited ones). This would be handy because no joins would be needed to an operation such as get.
Also see Django's documentation on model inheritance.
Just wanted to add something which I haven't seen in other answers.
Unlike with python classes, field name hiding is not permited with model inheritance.
For example, I have experimented issues with an use case as follows:
I had a model inheriting from django's auth PermissionMixin:
class PermissionsMixin(models.Model):
"""
A mixin class that adds the fields and methods necessary to support
Django's Group and Permission model using the ModelBackend.
"""
is_superuser = models.BooleanField(_('superuser status'), default=False,
help_text=_('Designates that this user has all permissions without '
'explicitly assigning them.'))
groups = models.ManyToManyField(Group, verbose_name=_('groups'),
blank=True, help_text=_('The groups this user belongs to. A user will '
'get all permissions granted to each of '
'his/her group.'))
user_permissions = models.ManyToManyField(Permission,
verbose_name=_('user permissions'), blank=True,
help_text='Specific permissions for this user.')
class Meta:
abstract = True
# ...
Then I had my mixin which among other things I wanted it to override the related_name of the groups field. So it was more or less like this:
class WithManagedGroupMixin(object):
groups = models.ManyToManyField(Group, verbose_name=_('groups'),
related_name="%(app_label)s_%(class)s",
blank=True, help_text=_('The groups this user belongs to. A user will '
'get all permissions granted to each of '
'his/her group.'))
I was using this 2 mixins as follows:
class Member(PermissionMixin, WithManagedGroupMixin):
pass
So yeah, I expected this to work but it didn't.
But the issue was more serious because the error I was getting wasn't pointing to the models at all, I had no idea of what was going wrong.
While trying to solve this I randomly decided to change my mixin and convert it to an abstract model mixin. The error changed to this:
django.core.exceptions.FieldError: Local field 'groups' in class 'Member' clashes with field of similar name from base class 'PermissionMixin'
As you can see, this error does explain what is going on.
This was a huge difference, in my opinion :)
The main difference is when you inherit the User class. One version will behave like a simple class, and the other will behave like a Django modeel.
If you inherit the base "object" version, your Employee class will just be a standard class, and first_name won't become part of a database table. You can't create a form or use any other Django features with it.
If you inherit the models.Model version, your Employee class will have all the methods of a Django Model, and it will inherit the first_name field as a database field that can be used in a form.
According to the documentation, an Abstract Model "provides a way to factor out common information at the Python level, whilst still only creating one database table per child model at the database level."
I will prefer the abstract class in most of the cases because it does not create a separate table and the ORM does not need to create joins in the database. And using abstract class is pretty simple in Django
class Vehicle(models.Model):
title = models.CharField(...)
Name = models.CharField(....)
class Meta:
abstract = True
class Car(Vehicle):
color = models.CharField()
class Bike(Vehicle):
feul_average = models.IntegerField(...)

Django: How to define the models when parent model has two foreign keys come from one same model?

I want to define two model fields: created_by, modified_by in a parent model, they will be acting as common fields for the child models.
class ExtendedModel(models.Model):
created_by = models.ForeignKey(User,related_name='r_created_by')
modified_by = models.ForeignKey(User,related_name='r_modified_by')
class Meta:
abstract = True
class ChildModel1(ExtendedModel):
pass
class ChildModel2(ExtendedModel):
pass
this gives errors as ChildModel1 and ChildModel2 has related_name clashed with each other on their created_by and modified_by fields.
The Django docs explain how to work around this: http://docs.djangoproject.com/en/dev/topics/db/models/#abstract-related-name
class ExtendedModel(models.Model):
created_by = models.ForeignKey(User,related_name='"%(app_label)s_%(class)s_created_by')
modified_by = models.ForeignKey(User,related_name='"%(app_label)s_%(class)s_modified_by')
class Meta:
abstract = True
class ChildModel1(ExtendedModel):
pass
class ChildModel2(ExtendedModel):
pass

Categories

Resources