I have two models: Seller
and Product
.
Each product has a foreignKey to a seller. So each product only has one
seller, but a seller can be related to many
products.
This is the ForeignKey in my Product
-Class:
seller = models.ForeignKey(
Seller,
on_delete=SET_NULL,
null=True,
related_name="products",
)
Now I try to query all Sellers and have the related products for each seller with them.
sellers = (
Seller.objects.filter(
..doing some filtering
).prefetch_related("products").filter(products__branch=current_branch)
)
By doing this, my sellers
has multiple entries for many sellers as I am filtering on the prefetche_related products resulting in a join inside the database-query.
What would be the best way to end up with a List of Sellers, each of them having their list of products with them? Without duplicates. I still need to filter on the products as I don’t want all the products to be queried.
1