如何使用django-tastypie查询ToManyField的属性

问题描述 投票:0回答:1

编辑:这种方法确实有效,我有一个错字。谢谢@eran指出来,修复如下。

在控制台中我可以这样做:

Performance.objects.filter(ticket_blocks__price__gt=200)

并获得价格超过200美元的票房。但是这个:

http://localhost:8000/api/v1/performance/?ticket_blocks__price__gt=200

给我KeyError: u'price'。我究竟做错了什么?

models.朋友

class TicketBlock(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=8, decimal_places=2)

class Performance(models.Model):
    start_time = models.DateTimeField(db_index=True)
    end_time = models.DateTimeField(default=None, blank=True, null=True)
    sold_out = models.BooleanField(default=False)

    # All performance have at least one ticket block
    ticket_blocks = models.ManyToManyField('TicketBlock')

API.朋友

class TicketBlockResource(ModelResource):
    class Meta:
        queryset = TicketBlock.objects.all()
        allowed_methods = ['get']
        resource_name = 'ticket-block'
        filtering = {
            'price': ALL
        }

class PerformanceResource(ModelResource):
    ticket_blocks = fields.ToManyField(TicketBlockResource, 'ticket_blocks', blank=True, null=True, full=True)

    class Meta:
        queryset = Performance.objects.all()
        allowed_methods = ['get']
        resource_name = 'performance'
        filtering = {
            'ticket_blocks': ALL_WITH_RELATIONS
        }
python django tastypie django-queryset
1个回答
0
投票

它应该工作,我认为你只是在定义中混淆并使用错误的模型VenueType而不是TicketBlock

换行:

queryset = VenueType.objects.all()

至:

TicketBlock.objects.all()

而且我认为它会解决你的问题。

© www.soinside.com 2019 - 2024. All rights reserved.