Django Group By не работает с несколькими объединениями - PullRequest
0 голосов
/ 14 апреля 2020

У меня проблема с группировкой записей с набором запросов, имеющим несколько объединений в Django ORM. Он отлично работает при выполнении необработанного запроса sql. Ниже приведены модели, sql необработанный запрос и моя попытка Django ORM для соответствующего запроса.

model.py

class Merchants(models.Model):
    id = models.IntegerField(primary_key=True)
    prospectId = models.CharField(max_length=50, default=None)
    merchantAmount = models.FloatField(null=True, blank=True, default=None)
    lenderName = models.CharField(max_length=10, default=None)
    requestedLoanAmount = models.FloatField(blank=True, default=None)
    createdDate = models.DateTimeField(default=None)
    storeId = models.IntegerField(unique=True, default=None)
    eStatus = models.CharField(max_length=10, default=None)
    loanBookingDate = models.DateField(default=None)
    dueLoanAmount = models.FloatField(default=None)
    totalRepayAmount = models.FloatField(default=None)
    los_loanApplicationId = models.CharField(max_length=50, default=None)
    modifiedDate = models.DateTimeField(default=None)
    loanStatus = models.CharField(max_length=20, default=None)
    LLA_LLMM = models.ForeignKey(LOS_Loan_Application, on_delete=models.CASCADE, db_column='los_loanApplicationId', to_field='loanApplicationId', default=None)

    class Meta:
        db_table = "loan_lending_mca_merchants"
        verbose_name_plural = "Merchants"


class Agent_Task_Log(models.Model):
    iVisitId = models.IntegerField(primary_key=True)
    iTaskId = models.IntegerField(default=None)
    ePaymentMode = models.CharField(max_length=30, default=None)
    iAmount = models.IntegerField(default=None)
    iStoreId = models.IntegerField(unique=True, default=None)
    dupdation_date = models.DateTimeField(default=None)
    store = models.ForeignKey('trx_insight.Store', on_delete=models.CASCADE, db_column='iStoreId', default=None)
    collection_dpd = models.ForeignKey(Collection_DPD, on_delete=models.CASCADE, db_column='iStoreId', to_field='iStoreId')

    class Meta:
        db_table = "agent_task_log"
        verbose_name = "Agent Task Log"


class Agents_Task(models.Model):
    iAgentTaskId = models.IntegerField(primary_key=True)
    iStoreId = models.IntegerField(unique=True, default=None)
    iAgentId = models.IntegerField(default=None)
    iTaskTypeId = models.IntegerField(unique=True, default=None)
    iAssignedBy = models.IntegerField(default=None)
    tCreationDate = models.DateTimeField(default=None)
    tUpdationDate = models.DateTimeField(default=None)
    tasksLog = models.ForeignKey(Agent_Task_Log, on_delete=models.CASCADE, db_column="iStoreId", to_field="iStoreId", default=None)

    class Meta:
        db_table = "agents_task"
        verbose_name_plural = "Agents Task"



class Tasks_Master(models.Model):
    iTaskMasterId = models.IntegerField(primary_key=True)
    vTaskType = models.CharField(max_length=30, default=None)
    tasks = models.ForeignKey(Agents_Task, on_delete=models.CASCADE, db_column='iTaskMasterId', to_field='iTaskTypeId', default=None)

    class Meta:
        db_table = "task_master"
        verbose_name = "Task Master"

views.py

class collections_details(viewsets.ModelViewSet):

        queryset = Merchants.objects.using('ftcash_db').raw("\
            SELECT l.id, l.prospectId AS 'prospectId', l.storeId AS 'iStoreId', s.vStoreName AS 'vStoreName', s.vStorePhone AS 'vStorePhone', l.requestedLoanAmount AS 'requestedLoanAmount', l.dueLoanAmount AS 'dueLoanAmount', dpd.fOverallDue AS 'fOverallDue', dpd.iDpd AS 'iDpd', alog.ePaymentMode AS 'ePaymentMode', alog.iAmount AS 'iAmount', atask.iAgentId AS 'iAgentId', alog.dupdation_date AS 'dupdation_date', l.loanBookingDate AS 'loanBookingDate', l.eStatus AS 'eStatus' FROM loan_lending_mca_merchants AS l \
                INNER JOIN store AS s ON s.iStoreId = l.storeId \
                    INNER JOIN collection_dpds AS dpd ON dpd.iStoreId = s.iStoreId \
                        INNER JOIN agent_task_log AS alog ON alog.iStoreId = s.iStoreId \
                            INNER JOIN agents_task AS atask ON atask.iStoreId = alog.iStoreId \
                                INNER JOIN task_master AS tm ON tm.iTaskMasterId = atask.iTaskTypeId \
                                    WHERE l.loanBookingDate BETWEEN '2019-01-01' AND '2020-01-01' \
                                        GROUP BY l.prospectId \
                                            ORDER BY dpd.iDpd DESC;")
serializer_class = collections_details_serializer

Я пытался написать набор запросов в Django ORM, но он не группируется по prospectId.

queryset = Tasks_Master.objects.using('ftcash_db').filter(tasks__tasksLog__store__merchants__loanBookingDate__range=[start, end]).values(prospectId=F('tasks__tasksLog__store__merchants__prospectId'))\
                .annotate(storeId=F('tasks__tasksLog__store__merchants__storeId'), requestedLoanAmount=F('tasks__tasksLog__store__merchants__requestedLoanAmount'), \
                    dueLoanAmount=F('tasks__tasksLog__store__merchants__dueLoanAmount'), vStoreName=F('tasks__tasksLog__store__vStoreName'), vStorePhone=F('tasks__tasksLog__store__vStorePhone'),\
                        fOverallDue=F('tasks__tasksLog__collection_dpd__fOverallDue'), iDpd=F('tasks__tasksLog__collection_dpd__iDpd'), ePaymentMode=F('tasks__tasksLog__ePaymentMode'),\
                            iAmount=F('tasks__tasksLog__iAmount'), dupdation_date=F('tasks__tasksLog__dupdation_date'), iAgentId=F('tasks__iAgentId'), \
                                loanBookingDate=F('tasks__tasksLog__store__merchants__loanBookingDate'), eStatus=F('tasks__tasksLog__store__merchants__eStatus')).order_by('-tasks__tasksLog__collection_dpd__iDpd')

Что я делаю не так?

Заранее спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...