Using custom methods in filter with django-rest-framework

后端 未结 2 1266
耶瑟儿~
耶瑟儿~ 2021-02-19 10:45

I would like to filter against query params in my REST API - see django docs on this. However, one parameter I wish to filter by is only available via a model @property

2条回答
  •  南笙
    南笙 (楼主)
    2021-02-19 11:19

    For sake of database speed, you should just add the category to your listing model

    class Listing(models.Model):
        product = models.OneToOneField(Product, related_name='listing')
        category = models.ForeignKey(Category)
    

    Then use a post_save signal to keep the field updated

    from django.dispatch import receiver
    from django.db.models.signals import post_save
    
    @receiver(post_save, sender=Product)
    def updateCategory(sender, instance, created, update_fields, **kwargs):
        product = instance
        product.listing.category = product.assets[0].category.name
        product.listing.save()
    

    Then filter by it's name as you would any other field:

    class ListingFilter(django_filters.FilterSet):
        ...
        category = django_filters.CharFilter(name='category__name')
        ...
    

提交回复
热议问题