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

时间:2014-02-20 15:05:24

标签: python django tastypie django-queryset

编辑:这种做法确实有效,我有一个错字。感谢@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.py

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.py

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
        }

1 个答案:

答案 0 :(得分:0)

IT应该有效,我认为您只是在定义中混淆并使用了错误的模型VenueType而不是TicketBlock

更改行:

queryset = VenueType.objects.all()

为:

TicketBlock.objects.all()

我觉得它会解决你的问题。