Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your example seems to sit between two different ways you can go, but is currently not correct. What is happening is that you are creating two tables: Product, and Mattress, and they are completely unrelated. Regardless of the fact that Mattress subclasses Product, it is just inheriting its structure. You cannot query anything in the Product table about a mattress because a mattress is in the Mattress table.</p> <p>One way to go is to consider a Product just abstract, to be subclassed by actual products:</p> <pre><code>class Product(RandomPrimaryIdModel): class Meta: abstract=True </code></pre> <p>This will prevent a Product table from being created. Then you would directly query a mattress via: <code>Mattress.objects.filter()</code></p> <p>But this seems a bit limiting in terms of introducing many types of products, and having to manage different tables for them. The other way to go is to use a Product table, but use generic relations to support attaching any type of other table as a content object:</p> <pre><code>from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Product(RandomPrimaryIdModel): feature1 = models.CharField(max_length=20, blank=True, null=True) feature2 = models.CharField(max_length=20, blank=True, null=True) feature3 = models.CharField(max_length=20, blank=True, null=True) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') </code></pre> <p>With this, you would be able to set the <code>content_object</code> to be a Mattress instance. You can then use the ContentType to query:</p> <pre><code>p_type = ContentType.objects.get(name="mattress") Product.objects.filter(content_type=p_type) </code></pre>
 

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