如何在DRF中将Django filter_fields与ArrayField一起使用

时间:2019-05-22 08:05:43

标签: django django-rest-framework django-filter

我在模型中使用了Postgres ArrayField。我正在尝试使用Django过滤器,但它们出现错误。

通过“精确”查找将AutoFilterSet解析的字段“风味”查找为无法识别的字段类型ArrayField。尝试将替代添加到“ Meta.filter_overrides”。参见:https://ibb.co/xqwT1hR

型号

                    <?php

                        $args = array(
                            'numberposts' => 5,
                            'offset' => 0,
                            'category' => '',
                            'orderby' => 'post_date',
                            'order' => 'DESC',
                            'include' => '',
                            'exclude' => '',
                            'meta_key' => '',
                            'meta_value' =>'',
                            'post_type' => 'post',
                            'post_status' => 'draft, publish, future, pending, private',
                            'suppress_filters' => true
                        );

                        $recent_posts = wp_get_recent_posts( $args, ARRAY_A );

                        foreach($recent_posts as $post):
                            if($post['post_category'] == 1):
                                echo "<p><i class=\"fas fa-book\">&nbsp;&nbsp;</i>{$post['post_title']}<br></p>";
                            elseif($post['post_category'] == 2):
                                echo "<p><i class=\"fas fa-desktop\">&nbsp;&nbsp;</i>{$post['post_title']}<br></p>";
                            endif;
                            echo $post['post_category']; //Debug, no output.
                            echo $post['post_title']; //Debug, output: "example post"
                            echo $post['post_date']; //Debug, output: "2019-05-21"
                        endforeach;

                        ?>

ViewSet

class Items(models.Model):
    item = models.CharField(max_length=150, unique=True)
    matches = ArrayField(models.CharField(
        max_length=200), blank=True, default=list)
    category = ArrayField(models.CharField(
        max_length=200), blank=True, default=list)
    flavor = ArrayField(models.CharField(
        max_length=200), blank=True, default=list)
    special = ArrayField(models.CharField(
        max_length=200), blank=True, default=list)
    created_at = models.DateTimeField(auto_now_add=True)

2 个答案:

答案 0 :(得分:1)

我想通了,大声笑。需要使用lookup_exp ='icontains'创建自定义过滤器。

class CategoryFilter(filters.FilterSet):
    category = filters.CharFilter(lookup_expr='icontains')

    class Meta:
        model = Items
        fields = ('item', 'category')
class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Items.objects.all()
    serializer_class = CategorySerializer
    filterset_class = CategoryFilter

答案 1 :(得分:0)

别忘了

import django_filters as filters

,因为您没有使用原始名称。我还必须将字段更改为方括号。

fields = ['item', 'category']