Друзья, подскажите.
Переписываю вьюхи под REST. Столкнулся с проблемой, что при использовании raw sql возникает много дублей.
class Supplier(models.Model):
name = models.CharField(max_length=512)
short_name = models.CharField(max_length=100, unique=True)
official_short_name = models.CharField(max_length=100, blank=True)
inn = models.CharField(max_length=12, blank=True)
kpp = models.CharField(max_length=9, blank=True)
ogrn = models.CharField(max_length=15, blank=True)
address = models.TextField(blank=True)
docgroup = models.ForeignKey(DocGroup, on_delete=models.SET_NULL, blank=True, null=True)
suppliergroup = models.ManyToManyField(SupplierGroup, blank=True, related_name="supplier")
comment = models.TextField(blank=True)
owner = models.ManyToManyField(User, blank=True)
def get_absolute_url(self):
return reverse('supplier_detail_url', kwargs={'pk': self.pk})
class Meta:
verbose_name = "Контрагент"
verbose_name_plural = "Контрагенты"
def __str__(self):
return self.short_name
class SupplierListSerializer(serializers.ModelSerializer):
class Meta:
model = Supplier
fields = ('id', 'name', 'short_name')
def to_representation(self, instance):
data = super(SupplierListSerializer, self).to_representation(instance)
data['from_amount'] = instance.from_amount
data['to_amount'] = instance.to_amount
return data
class SupplierListView(generics.ListCreateAPIView):
serializer_class = SupplierListSerializer
def list(self, request, *args, **kwargs):
raw_sql = '''SELECT id, short_name, inn, comment, sp.position, tr_s_1.from_amount, tr_s_2.to_amount
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
LEFT JOIN (
SELECT SUM(amount) as from_amount, supplier_1_id
FROM accounting_transaction WHERE date>= %s and date<= %s
GROUP BY supplier_1_id) as tr_s_1
on tr_s_1.supplier_1_id = s.id
LEFT JOIN (
SELECT SUM(amount) as to_amount, supplier_2_id
FROM accounting_transaction WHERE date>= %s and date<= %s
GROUP BY supplier_2_id) as tr_s_2
on tr_s_2.supplier_2_id = s.id
GROUP BY short_name, inn, comment, sp.position, sp.supplier_id ORDER BY sp.position is NOT NULL DESC, sp.position ASC'''
profile = Profile.objects.get(user=request.user)
queryset = Supplier.objects.raw(raw_sql, [request.user.id, profile.start_date, profile.end_date, profile.start_date, profile.end_date])
serializer = SupplierListSerializer(queryset, many=True)
serialized_data = {'data': serializer.data}
serialized_data.update({'New field': 'New data'})
return Response(serialized_data)
Получаю вот такую ерунду:
Где туплю?