请求不返回时如何处理

时间:2019-08-08 20:22:25

标签: python django

我有一个IDs列表,它对应于数据库中的一组记录(机会)。然后,我将此列表作为RESTful API请求中的参数传递,在这里我用ID过滤结果(票证)。对于每个匹配项,查询将返回与单个记录有关的JSON数据。但是,我想处理查询找不到匹配项的情况。我想为这种情况分配一些值,例如字符串“ None”,因为并非每个opportunity都有一个ticket。如何确定presales_tickets中的每个IDopportunity_list中有某个值?在这种情况下,我可以在请求中提供默认值吗?

views.py

    opportunities = cwObj.get_opportunities()

    temp = []
    opportunity_list = []
    cw_presales_engineers = []

    for opportunity in opportunities:
        temp.append(str(opportunity['id']))
        opportunity_list = ','.join(temp)

    presales_tickets = cwObj.get_tickets_by_opportunity(opportunity_list)

    for opportunity in opportunities:
        try:
            if opportunity['id'] == presales_tickets[0]['opportunity']['id']:
                try:
                    for presales_ticket in presales_tickets:
                        cw_engineer = presales_ticket['owner']['name']
                        cw_presales_engineers.append(cw_engineer)
                except:
                    pass
            else:
                cw_engineer = 'None'
                cw_presales_engineers.append(cw_engineer)
        except AttributeError:
            cw_engineer = ''
            cw_presales_engineers.append(cw_engineer)

1 个答案:

答案 0 :(得分:0)

因此,假设您有一个票证模型和一个机会模型。通过外键连接。

class Opportunity(models.Model):
    ... some fields here ...

class Ticket(models.Model):
    opportunity = models.ForeignKey(Opportunity)

在您看来,您会获得机会ID列表

def some_view(request):
    ids = request.GET['ids']

听起来,您想要的是为所提供的机会获取所有票证,并为没有票证的机会添加一些默认处理。如果是这样,为什么不做类似的事情

def some_view(request):
    ids = request.GET['ids']
    tickets = Ticket.objects.filter(opportunity__id__in=ids)
    results = []
    for ticket in tickets:
        result = ... do your thing here ...
        results.append(result)
    # now handle missing opportunities
    good_ids = tickets.values_list('opportunity__id', flat=True).distinct()
    for id in ids:
        if id not in good_ids:
            result = ... do your default processing ...
            results.append(result)

这是您要做什么吗?