【问题标题】:How to query on attribute of ToManyField with django-tastypie如何使用 django-tastypie 查询 ToManyField 的属性
【发布时间】:2014-03-21 14:56:27
【问题描述】:

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

【问题讨论】:

    标签: python django tastypie django-queryset


    【解决方案1】:

    它应该可以工作,我认为您只是对定义有混淆并使用了错误的模型VenueType 而不是TicketBlock

    换行:

    queryset = VenueType.objects.all()
    

    到:

    TicketBlock.objects.all()
    

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

    【讨论】:

      猜你喜欢
      • 2013-01-03
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      相关资源
      最近更新 更多