Can a django model have two abstract classes? - django

I have this models:
class BillHeader(models.Model):
billno = models.IntegerField(primary_key=True, blank=True)
class BillData(models.Model):
price = models.DecimalField(_('Price'), max_digits=12, decimal_places=2)
amount = models.DecimalField(_('Amount'), max_digits=6, decimal_places=2)
[... rest of the model ...]
class Meta:
abstract = True
class BillFooter(models.Model):
total = models.DecimalField(_('Total'), max_digits=12, decimal_places=2)
[... rest of the model ...]
class Meta:
abstract = True
BillData and BillFooter are common to every BillHeader so I've marked them as abstract. Can I do class BillHeader(BillData, BillFooter) or I'm doing something wrong?
I also thought about doing BillData the main one, and BillHeader BillFooter abstract. I don't have any experience on doing data models (at least not complex ones) and I'm a bit lost. What would you recommend?

Yes, a Django model can inherit from as many abstract base classes as you like, as long as they don't result in an ambiguous "model resolution order". Think of inheritance as a chain... each class you inherit from is a link in the chain. Inheriting from two base classes is just adding two links to the chain instead of one.
In other words, if your abstract base classes inherit from models.Model, then don't try to inherit from both the abstract base class and models.Model in your Bill class. models.Model is already in the inheritance chain, so inheriting from it causes chaos in the chain of base classes.
As to how I would structure these classes, I would create a model called Bill that inherited from BillHeader, BillData, and BillFooter. The reason for this is that I like my Django models to represent discrete objects (e.g. Bill, Article, BlogPost, Photo, etc.)
However, the point of abstract base classes is to be able to add a level of abstraction to common fields and methods so that multiple classes can inherit from them. If you're just creating a Bill class it's somewhat meaningless. If, however, you had Bill, and UnpaidBill, and PaidBill... all of those would have common fields that should appear on all of them and you can save yourself a lot of trouble by abstracting to an ABC.
Hopefully that offers a little insight to what ABC's and inheritance are good for.

Related

Abstract model with dynamic fields

I am wondering since ages how to achieve the following:
I have an abstract class wrapping several attributes shared by multiple models. But not every model needs every attribute in exactly the same way.
Here is an example: MyModelA and MyModelB both have two fields: value_1 and value_2. But while MyModelA needs them to be required/not nullable, they can be nullable for MyModelB.
class MyAbstractModel(models.Model):
value_1 = models.IntegerField()
value_2 = models.IntegerField()
class Meta:
abstract = True
What I tried:
Not deriving MyAbstractModel from models.Model but from object like a regular mixin
Setting a class attribute which is overwritten in the child classes to determine the nullable-state. It always takes the definition from MyAbstractModel.
Using a class attribute but not set it in the MyAbstractModel. Then the makemigrations command fails because of the undefined variable.
Cry
Being DRY is such an important paradigm in django, I really wonder that there is nothing on this topic in the internet.
Thanks in advance!

Wagtail Inline Panel - Sort Order

So I'm struggling with ordering the choices within an InlinePanel (for an orderable) on my site. In the admin page, when adding a new item, the options are presented in the order they were added to the site (so, essentially the 'id' for that item); this is less than ideal considering there are hundreds of options presented in a manner that is not user friendly.
I'm assuming this needs to be defined as ordering meta within the orderable, but I can't seem to get it to work. This is what my orderable looks like:
class RelatedPeople(Orderable):
service = ParentalKey('service.Services', related_name='related_person')
person = models.ForeignKey('person.People', null=True, on_delete=models.SET_NULL, related_name='related_service')
panels = [
FieldPanel('person')
]
I've tried the following with no success:
class Meta:
ordering = 'person'
and, trying to append the field within 'person' that I want to sort by, 'name':
class Meta:
ordering = 'person.name'
There must be an obvious way to solve this that I'm over looking. A default sort order of the 'id' (in this case, for 'person.People') is rarely ever going to be suitable from the perspective of the content creator.
Any advice would be greatly appreciated!
Thanks in advance,
Rob
Person model should have:
ordering = ['name']
instead of
ordering = 'name'
And your Orderable object should have it's meta changed to
class Meta(Orderable.Meta):
Via Django Docs, this is the example of abstract base classes, and ordering:
Meta and multi-table inheritance¶
In the multi-table inheritance situation, it doesn’t make sense for a
child class to inherit from its parent’s Meta class. All the Meta
options have already been applied to the parent class and applying
them again would normally only lead to contradictory behavior (this is
in contrast with the abstract base class case, where the base class
doesn’t exist in its own right).
So a child model does not have access to its parent’s Meta class.
However, there are a few limited cases where the child inherits
behavior from the parent: if the child does not specify an ordering
attribute or a get_latest_by attribute, it will inherit these from its
parent.
If the parent has an ordering and you don’t want the child to have any
natural ordering, you can explicitly disable it:
class ChildModel(ParentModel):
# ...
class Meta:
# Remove parent's ordering effect
ordering = []
When an abstract base class is created, Django makes any Meta inner
class you declared in the base class available as an attribute. If a
child class does not declare its own Meta class, it will inherit the
parent’s Meta. If the child wants to extend the parent’s Meta class,
it can subclass it. For example:
from django.db import models
class CommonInfo(models.Model):
# ...
class Meta:
abstract = True
ordering = ['name']
class Student(CommonInfo):
# ...
class Meta(CommonInfo.Meta):
db_table = 'student_info'
I am not familiar with Wagtail, but can you take a look at this issue :
https://github.com/wagtail/wagtail/issues/4477#issuecomment-382277375
Update:
Maybe you just need to update your Person model like this:
class Person(models.Model):
...
class Meta:
ordering = 'name'
In your files, you try to order RelatedPeople by Person, but what you need is to order the Person list by name in your wagtail dropdown

Inherit a class but only use required fields ,not all inherited fields

Suppose there are total 3 class. A,B and C.
class A(models.Model):
one = models.IntegerField()
two = models.IntegerField()
three = models.IntegerField()
class Meta:
abstract = True
class B(A):
pass
class C(A):
pass
I am inheriting the class A in B and C,but i want to use only fields one and two in classB while all the three fields in classC.
Is it possible to inherit some fields of classA in classB and some in classC?
or is it a bad idea?
As you may already know, there are three types of inheritance across models in django.
Often, you will just want to use the parent class to hold information that you don’t want to have to type out for each child model. This class isn’t going to ever be used in isolation, so Abstract base classes are what you’re after.
If you’re subclassing an existing model (perhaps something from another application entirely) and want each model to have its own database table, Multi-table inheritance is the way to go.
Finally, if you only want to modify the Python-level behavior of a model, without changing the models fields in any way, you can use Proxy models.
The only choice for your use-case is abstract base classes.
And the thing you are looking for from docs:
Fields inherited from abstract base classes can be overridden with another field or value, or be removed with None.
So you should have:
class A(models.Model):
one = models.IntegerField()
two = models.IntegerField()
three = models.IntegerField()
class Meta:
abstract = True
class B(A):
three = None
class C(A):
three = None
And to answer your second question, It's not a bad idea; We normally use it when we want to change the USERNAME_FIELD while extending django's default user model.

How to get objects from two different tables that have a relationship to a third table using the related names in Django?

Let me explain. I have 2 tables which are child classes of another abstract table. The abstract table has a relationship to a model called Foo. The related_name is set dynamically. The code looks like this:
class Foo(models.Model):
...
class Parent(models.Model):
foo = models.ForeignKey(
Foo,
on_delete=models.CASCADE,
related_name='%(app_label)s_%(class)s_related'
)
...
def bar(self):
print('bar')
class Meta:
abstract = True
class ChildOne(Parent):
...
class ChildTwo(Parent):
...
Therefore, the related names become 'myapp_childone_related', and 'myapp_childtwo_related'.
Now, lets say I want to call the bar() method of all the objects from the ChildOne and ChildTwo model that is related to a Foo object. There is a catch though, I want to it from with a class method of the Foo model. Currently, I'm doing it like this:
class Foo(models.Model):
...
def call_bar(self):
references = ('childone', 'childtwo')
for ref in references:
children = getattr(self, f'myapp_{ref}_related').all()
for child in children:
child.bar()
This works fine, but honestly feels a bit hack-y, especially when dealing with more than two children classes. Is there a nicer, more Pythonic solution to this problem?
Edit: I decided not to mention previously that I wanted to call the bar() method from within a class method of the Foo model because I thought that it was unnecessary for this question. However, Daneil Roseman's answer suggested making a list of classes, which is a good solution, but it would not work within the class method, as the classes have not yet been defined at that point in the module. So mentioning that in this edit.
A related_name is only syntactic sugar for performing a query from the related class itself. So you should just do this explicitly:
child_classes = [ChildOne, ChildTwo]
for child_class in child_classes:
children = child_class.objects.filter(foo=foo)

Django model inheritance, filtering models

Given the following models:(don't mind the TextFields there're just for illustration)
class Base(models.Model):
field1 = models.TextField()
class Meta:
abstract=True
class Child1(Base):
child1_field = models.TextField()
class Child2(Base):
child2_field = models.TextField()
class Content(models.Model):
aso_items = models.ManyToManyField('Base')
According to these definitions a Content object can be associated with more than one Base object, eg. an interview(=Content object) can be linked with a musician(=Child1 object), a filmdirector(=Child2), etc.
Now, for my question:
Is it possible to filter Content objects according to which model the aso_items field points to?
An example : Say I would like a Queryset containing all the Content objects that are associated with a specific object of Child1(eg. all the interviews associated with the musician Bob Dylan), how can I achieve this?
Further, what if I'd want a QuerySet containing all the Content objects that are associated with Child1 objects?(eg. all the interviews that associated with musicians)
How does this change the filtering?
Thanks in advance
ps: I'm experiencing some problems with white space in the preview, forgive me
You should check the section of the Django docs regarding using related_name for abstract base classes. http://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name
To quote the docs:
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 be the string %(class)s. This
is replaced by the lower-cased name of
the child class that the field is used
in. Since each class has a different
name, each related name will end up
being different.
Using this information I would recommend moving the m2m field into the Base class:
class Content(models.Model):
# Add remaining fields for Content
pass
class Base(models.Model):
field1 = models.TextField()
items = models.ManyToManyField(Content,related_name="%(class)s_related")
class Meta:
abstract=True
class Child1(Base):
child1_field = models.TextField()
class Child2(Base):
child2_field = models.TextField()
Apparently a ForeignKey relation(or ManyToMany for that matter) with a abstract class isn't allowed.
I get the following error : 'AssertionError: ForeignKey cannot define a relation with abstract class Artiest'.
A possible solution is to define the base class as non-abstract, however this implies that one could instantiate models of the base class. Which isn't the behavior I want.(after all it was an abstract class)
Has someone come accross the same problem how did you solve it? Any alternatives?
Have a look at http://www.djangoproject.com/documentation/models/generic_relations/ which goes through generic relations. Your Content model would match up to their TaggedItem model, and your Base model would match up to their Animal/Vegetable/Mineral model (with Child1 and Child2 extending).
Getting all of the Content objects for a single child would be (assuming you set the GenericRelation to contents inside Base):
child_contents = childObject.contents.all()
And to get all Content objects for a model:
ctype = ContentType.objects.get_for_model(Child1)
all_child_contents = Content.objects.filter(content_type=ctype)