I am looking to organise products within categories in a way that is specific to the selected category. A product can be part of multiple categories and so I'm using a Many-To-Many Through relationship to define them.
I have the following 4 models:
class Category(MPTTModel, ModelWithMetadata, SeoModel, PublishableModel):
name = models.CharField(max_length=512)
...
class Product(SeoModel, ModelWithMetadata, PublishableModel):
name = models.CharField(max_length=512)
category_management = models.ManyToManyField(
Category,
related_name="category_managed_products",
through="OrderedCategoryManagedProduct",
blank=True,
verbose_name="Category Management",
)
...
class OrderedCategoryManagedProduct(SortableModel):
category = models.ForeignKey(
Category, on_delete=models.CASCADE, related_name="cmp_products"
)
product = models.ForeignKey(
Product, on_delete=models.CASCADE, related_name="cmp_categories"
)
added_automatically = models.BooleanField(default=False)
class Meta:
ordering = ["sort_order"]
def get_ordering_queryset(self):
return OrderedCategoryManagedProduct.objects.all()
class SortableModel(models.Model):
sort_order = models.IntegerField(editable=False, db_index=True, null=True)
class Meta:
abstract = True
def get_ordering_queryset(self):
raise NotImplementedError("Unknown ordering queryset")
...
The SortableModel is from the Saleor Legacy Views application
Is it possible to query a particular category and receive a queryset of the products within it in - ordered by sort_order
- without having to iterate through all the products individually?