Answer the question
In order to leave comments, you need to log in
How to make a left join distinct selection (DB: mysql)?
Initial task:
there is a group of counterparties, there are users. Each user has his own sorting of counterparties.
class Supplier(models.Model):
name = models.CharField(max_length=512)
short_name = models.CharField(max_length=100, unique=True)
class SupplierPosition(models.Model):
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
position = models.PositiveIntegerField()
SELECT * FROM accounting_supplier as s
LEFT JOIN ( SELECT * FROM accounting_supplierposition WHERE user_id = 1 ) as sp
on sp.supplier_id = s.id;
objects.raw("SELECT * FROM accounting_supplier as s LEFT JOIN
( SELECT position, supplier_id FROM accounting_supplierposition WHERE user_id = %s ) as sp
on sp.supplier_id = s.id ORDER BY sp.position", [request.user])
Answer the question
In order to leave comments, you need to log in
objects.raw("SELECT * FROM accounting_supplier as s LEFT JOIN
( SELECT position, supplier_id FROM accounting_supplierposition WHERE user_id = %s ) as sp
on sp.supplier_id = s.id ORDER BY sp.position", [request.user.id])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question