Andrew Medvedsky
Andrew Medvedsky

Reputation: 93

How to order by nested objects fields?

I have some classes

class MarketProduct(models.Model, ObjectMarket):
    _state_class = 'MarketProductState'

    uuid = models.UUIDField(u'Код',
                        default=uuid.uuid4, editable=False)
    name = models.CharField(u'Название',
                        max_length=255, db_index=True)
class MarketItem(models.Model, ObjectMarket):
    _state_class = 'MarketItemState'

    STOCK, AUCTION = 1, 2
    ITEM_CHOICES = (
        (STOCK, u'Сток'),
        (AUCTION, u'Аукцион'),
    )

    product = models.ForeignKey(MarketProduct)
    start_at = models.DateTimeField(u'Начало продажи')

I want to get MarketItemViewSet and use

filter_backends = (filters.OrderingFilter,`)

I send request with filed orderby by angular. If I send orderby = start_at, all are good, but I want to send orderby = product.id, it doesn't work.

Upvotes: 4

Views: 3470

Answers (2)

Aameer
Aameer

Reputation: 1376

As you are using django-rest-framework you have to use ordering_fields as you can see from the documentation here.Hope it helps example:

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('username', 'email')
    ordering = ('created_on') # for reverse ordering = ('-created_on')

If an ordering attribute is set on the view, this will be used as the default ordering.

Typically you'd instead control this by setting order_by on the initial queryset, but using the ordering parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template

Upvotes: 2

Rahul Gupta
Rahul Gupta

Reputation: 47876

You can try specifying product__id to perform ordering based on the id of product.

orderby = product__id

Specify ordering_fields in your viewset.

ordering_fields = ('product__id', )

Upvotes: 6

Related Questions