Model Inheritance - django

Which is better to use among all of the model inheritance and why? I do not have knowledge about it so I want to know which better, or more useful so that I will know which is I will use for that particular scenario.
abstract base classes
multi-table inheritance
proxy models

Each of these techniques provide different benefits. It really depends on what you need to do.
The best place to start is reading the model inheritance docs.
Abstract base classes
Use these if you're just trying to reduce the amount of code you write. If you know that several fields appear in numerous models then write a base class and inherit it.
Multi-table inheritance
This is useful if you want a concrete base class that can be queried and operated on - for example Base.objects.all() is a bit like seeing Child1.objects.all() and Child2.objects.all() in the same queryset.
Proxy Models
Use proxy models if all the fields are the same across each model. You get one db tuple for each object, but that db tuple can be used to represent either the parent or the proxy. This is quite powerful, and almost certainly the way to go if your fields are the same.

Related

Query only specific subclass(es) of an abstract superclass

This question is fundamentally similar to these previous questions:
Django access to subclasses items from abstract class
How to query abstract-class-based objects in Django?
I am posting this as a new, separate question because:
I have minor additional considerations that aren't addressed in the previous questions
The previous questions are relatively old, and if it's the case that the correct answer has changed in recent times, I wonder if maybe those questions haven't been visible enough (given that they have accepted answers) to get the attention of those who might know about such potential changes.
With that in mind, I'll take the question from the top and define it fully and concretely - and I leave it to the hive to determine if a close-duplicate is in order.
Background
Say I am constructing models to represent parts of a building. I split the building into logical classes:
Floor
BuildingSpace(ABC)
Office(BuildingSpace)
CommonArea(BuildingSpace)
Goal
Under Floor, I want methods that can retrieve all buildingspaces - or, either of its two subclasses separately:
from typing import Type
class Floor(models.Model):
def getAllSpaces():
# return all objects that satisfy Type[BuildingSpace]
def getAllOffices():
# return all objects that satisfy strictly and only Type[Office]
def getAllCommonAreas():
# return all objects that satisfy strictly and only Type[CommonArea]
Possible solutions
django-model-utils looks like it can support this kind of a query out-of-the-box with its InheritanceManager and the .select_subclass() method -- but, crucially, requires BuildingSpace to be concrete, so that leaves this solution with having to go with multi-table inheritance. Which I understand amplifies database load for each query, so I looked into making the subclasses proxies in order to mitigate that, but InheritanceManager doesn't support proxies. When all is said and done, django-model-utils look to me like it unavoidably opens me to multi-table inheritance penalties at query time.
django-polymorphic also supports this out-of-the-box as far as I have been able to glean, using .instance_of(subclass). Purely from a coding point-of-view, this approach looks very clean and easy to use. But it also looks to come with database performance considerations, and making it admin-panel compliant looks non-trivial at a first, superficial glance.
Natively, it looks django can do this in some roundabout way, but I've seen claims that achieving the same functionality as described above with a native QuerySet.filter() approach is worse performance-wise than both of the above extensions.
A final alternative solution I've briefly considered, that I assume will work natively without creating database considerations (but does require a slight redesign) - is to access the subclass managers directly, and then have the desired outcome of getAllSpaces() implemented via a QuerySet.Union-type of approach.
Almost-MRE
Naïve setup of how I had imagined to be able to use the code:
class BuildingSpace(models.Model):
floor = models.ForeignKey('Floor',
on_delete=models.CASCADE,
related_name="interiors")
class Meta:
abstract = True
class Floor(models.Model):
def _InteriorManager(self): # get the default manager of BuildingSpace
return self.interiors
def GetAllInteriors(self):
return self._InteriorManager().all() # get the full Type[BuildingSpace] queryset, but this isn't supported in native django
def GetOffices(self):
return self._InteriorManager().instance_of(Office) # django-polymorphic
def GetCommonAreas(self):
return self._InteriorManager().select_subclasses(CommonAreas).all() # django-model-utils
Question
I'm hoping to get answers that can weigh in on the following factors:
is there any significant difference in performance between django-model-utils, django-polymorphic and some other best-case QuerySet.filter()-based approach for the cases described here (and potentially, the linked questions at the top)
does either extension implicate any other consideration that is worth noting (ease of use, extensibility, how additional filtering is done, etc)
would my "final alternative solution" in the end maybe work better on all accounts (performance, ease of use, extensibility) if it is the case that the use-cases I need solved are never more complex than the concrete code examples I've provided
I have no insights as to the database performance topic as of yet, but I will say this:
django-polymorphic is really smooth to use. Minimal code adaptation required, and the syntax is both short and intuitive. The perceived difficulty of making it compliant with the admin-panel was a smokescreen, at least as long as you do basic, straightforward subclassing.
For anyone coming this way with similar troubles, don't hesitate to try it. You can't use it on abstract classes, as mentioned, but unless you have really particular needs it does look like having a concrete superclass and just using this library is a whole lot easier than jerry-rigging a manual solution similar to the one I described in the question.

Objects of class A in Class B in Class Diagram

I have an app with my own - user defined class and I also use Qt framework libraries to initiate objects of other classes that are built-in. So in my class let's call it 'myclass' I create instances of Qt built-in classes and work on them. THIS IS DONE ... Now, I need to create class diagram for that. I was wondering to which out of Association, Aggregation, Composition or Generalization this could this be classified as ?
Thanks
It is not generalization as you are not inheriting in here, so it cannot qualify as an "is-a" relationship.
As for association, composition or aggregation... here you can find a pretty good explanation which is which. It is not possible to tell the right one for you without knowing your use case better. However, reading the other link will help you to understand the differences and judge based on your scenario.
Difference between association, aggregation and composition
Hope that helps.
The important thing to keep in mind about UML is that there's often no actual right or wrong answer when deciding on what to use, but some tools are better than others. UML is simply a tool for communication and as long as the tool is used in a way that everyone understands what is being communicated, then it serves its purpose.
For a class diagram, at its most basic level, you could actually model everything with just Association and Generalisation, but then this would lack detail that others may want to see.
Generalisation has a one to one relationship with inheritance, so it's clear when to use that.
Association describes any class with a relationship or dependancy with another class; quite a generalisation there(!) which is why it could be used in replacement of Aggregation and Composition.
Aggregation is used when an object (B) makes up another object (A) and B can be shared amongst other objects. For example, a library consists of books, so a book could be modelled as an aggregate of the library because other classes, could also aggregate a book, such as the person borrowing it.
Use composition when an object (B) is used directly to make up an object (A). In this case, if you were modelling the human body and had classes of organs, you would model a heart class as a composition object of a body class.
The fact that you're using the Qt framework is irrelevant to what you use to model your classes and a diagram doesn't need to model everything, just what is necessary to communicate concepts to others.
If, for example you're using container classes such as QList and QMap, you probably don't even want those in the diagram, but if you were to use QTcpSocket and inherit from it, then it may be better to show that.
Just remember, it's all about what you're trying to communicate.

In ember.js, what's the difference between mixin and extend?

What's is the difference between mixin and extend, when to use each one?
I wrote this article about Ember.Object which explains the differences in detail. Essentially, use extend to create a new class from a base class and use mixins to separate lateral concerns that you may want to include in any number of classes / objects. Mixins can be included in classes via extend or objects via create.
A mixin is a special kind of multiple inheritance. There are two main situations where mixins are used:
You want to provide a lot of optional features for a class.
You want to use one particular feature in a lot of different
classes.

Cannot quite get my head around django mixins

I recently had a django question - and one of the answers left me stumped:
https://stackoverflow.com/a/10608687/1061426
I've read the django doco, but cannot quite work out how mixins are relevant to what was asked, or what the answer is referring to.
So, I searched for "django mixin tutorial" and stumbled across something called dajax and dajaxice. Ok, i am lying, i came across this blog:
http://www.pythondiary.com/blog/Apr.15,2012/stay-tuned-django-ajax-tutorial.html
My question is:
What are mixins? How do they relate to ajax calls? Are they used for things other than ajax? Why would i want to use dajax or dajaxice or some other django addin framework, rather than just plain django to work with ajax?
Also, there isn't a dajax tag, but there is a dajaxice tag for stackoverflow... does that mean that dajaxice is The Way To Go?
Cheers,
Mixins are a general Object Oriented Programming concept. They don't specifically have anything to do with Django or Dajax, etc. However, Django does, and Dajax probably as well, use mixins.
In general, a "mixin" is simply a class that is meant to literally be mixed in with another class. It typically doesn't do anything on its own, but rather, merely adds functionality to another class. Django's concept of "abstract" models are an example of a mixin. You never instantiate an abstract model. Instead, other models inherit from the abstract model, gaining all of its functionality, and it's those subclasses that actually are instantiated.
Django's class-based views (which is what the answer that brought you here is talking about) also use mixins. For example, most of the class-based views inherit from TemplateResponseMixin. This class is not a view itself, and you would never use it for anything but for a class-based view to inherit from. It's merely an encapsulation of all the functionality that renders a template into a response, so this functionally can be "mixed in" to all the various views without violating DRY (Don't Repeat Yourself).
No, mixins don't have anything in particular to do with Ajax.
A mixin is just a class that can be used as part of the multiple inheritance for another class. Django uses these extensively in its class-based views - some classes provide (for example) the basic functionality for displaying forms, or lists of models, and you are meant to mix those in with your own classes: create your own code that implements your own extensions to that functionality, while inheriting from one or more mixins.
I've never used Dajax, but I suppose it also uses mixins to provide the basic implementation of the Ajax handling within your views.

Mixing component based design and the model-view(-controller) pattern

'm developing a 2D game and I want separate the game engine from the graphics.
I decided to use the model-view pattern in the following way: the game engine owns game's entities (EnemyModel, BulletModel, ExplosionModel) which implement interfaces (Enemy, Bullet, Explosion).
The View receives events when entities are created, getting the pointer to the interface: in this way the View can only use the interface methods (i.e. ask for informations to perform the drawing) and cannot change the object state. The View has its onw classes (EnemyView, BulletView, ExplosionView) which own pointers to the interfaces.
(There is also an event-base pattern involved so that the Model can notify the View about entity changes, since a pure query approach is impraticable but I wont' discuss it here).
*Model classes use a compile-time component approach: they use the boost::fusion library to store different state componets, like PositionComponent, HealthComponent and so on.
At present moment the View isn't aware of the component based design but only of the model-view part: to get the position of an enemy it calls the Enemy::get_xy() method. The EnemyModel, which implements the interface, forwards this call to the PositionComponent and returns the result.
Since the bullet has position too, I have to add the get_xy method to Bullet too. BulletModel uses then the same implementation as the EnemyModel class (i.e. it forwards the call).
This approch then leads to have a lot of duplicate code: interfaces have a lot of similar methods and *Model classes are full of forward-methods.
So I have basically two options:
1) Expose the compoment based design so that each component has an interface as well: the View can use this interface to directly query the component. It keeps the View and the Model separated, only at a component level instead of a entity level.
2) Abandon the model-view part and go for pure component based design: the View is just a component (the RenderableComponent part) which has basically full access to the game engine.
Based on your experience which approach would be best?
I'll give my two cents worth. From the problem you're describing, it seems to me that you need an abstract class that will do the operations that are common amongst all of your classes (like the get_xy, which should apply to bullet, enemy, explosion, etc.). This class is a game entity that does the basic grunt work. Inheriting classes can override it if they want.
This abstract class should be the core of all your interfaces (luckily you're in C++ where there is no physical difference between a class, and abstract class and an interface). Thus the Views will know about the specific interfaces, and still have the generic entity methods.
A rule of thumb I have for design - if more than one class has the same data members or methods, it should probably be a single class from which they inherit.
Anyway, exposing the internal structure of your Model classes is not a good idea. Say you'll want to replace boost with something else? You'd have to re-write the entire program, not just the relevant parts.
MVC isn't easy for games as when the game becomes larger (including menu, enemies, levels, GUI...) and transitions, it'll break.
Component or entity-system are pretty good for games.
As a simpler case for you, you may consider using a HMVC. You'll still have issues with transitions, but at least your code will be grouped together in a more clean manner. You probably want your tank's code (rendering and logic) to get close together.
There have been presentation architectures designed especially for agent-based systems, such as Presentation-Abstraction-Control. The hard part in designing such a system is that you ultimately end up hardwiring sequences of collaborations between the agents.
You can do this, but don't use OO inheritance to model the message passing hierarchy. You will regret it. If you think about it, you are really not interested in using the OO inheritance relationship, since the interfaces defined are really just a "Record of functions" that the object can respond to. In that case, you are better off formally modeling your communication protocol.
If you have questions, please ask -- this is not an obvious solution and easy to get wrong.