Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to make a base class when childs can't inherit?
    text
    copied!<p>I have a fairly simple model in Django, let's say <code>Book</code>:</p> <pre><code>class Book(models.Model): name = models.CharField(max_length=255, default="") description = models.TextField(null=True, blank=True) creation_date = models.DateTimeField() </code></pre> <p>Because the structure and data basically comes from an external API, I have contained it in its own app and I rather not want to modify it.</p> <p>Now I want to add another source of different books to the project and I'm not really sure what the best solution is here.</p> <p>Let's say the second model is:</p> <pre><code>class NextBook(models.Model): title = models.CharField(max_length=255, default="") long_description = models.TextField(null=True, blank=True) created = models.DateTimeField() </code></pre> <p>So the basic fields are there, but have different names. To get the two together, I can probably use another model with a GenericForeignKey:</p> <pre><code>class BaseBook(models.Model): book_type = models.ForeignKey(ContentType) book_id = models.PositiveIntegerField() book_object = generic.GenericForeignKey('book_type', 'book_id') </code></pre> <p>But then I cannot query for all the book as e.g. <code>BaseBook.objects.all().order_by('created')</code> wouldn't work. Surely, I could go on and duplicate a datetime field in the base model and then the title and so on, but I think that would be the wrong direction. Also inheritance seems not a choice if I don't want to touch the specific models.</p> <p>I am looking for some design pattern or something that let's me efficiently 'plug in' more providers and query for all objects, while not making a huge mess of model structure and database queries.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload