0

我怎样才能提出 DRF 请求,就好像它就像按 LIKE 条件请求 SELECT 一样?现在它们像这样显示给我, 在此处输入图像描述 但我想根据 user_id 和 user_members_id 列中的值进行输出。我有这个代码

models.py

from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.contrib.auth.models import User

def user_directory_path(instance, filename): 
    # file will be uploaded to MEDIA_ROOT / user_<id>/<filename> 
    return 'user_{0}/{1}'.format(instance.company.id, filename)

# Create your models here.
class Company(models.Model):
    name = models.CharField(max_length=40, blank=True)
    user_id =  models.ForeignKey(User, verbose_name='User', on_delete=models.CASCADE) #models.IntegerField(blank=True)
    user_members_id = ArrayField(models.IntegerField(), blank=True)
    date_created= models.DateTimeField(auto_now=True)
    description = models.TextField(blank=True)
    # ready = models.CharField(max_length=10, blank=True)
    STATUSES = (
        (1, 'Public'),
        (2, 'Private'),
        (3, 'Protected'),
    )
    status = models.IntegerField(verbose_name='Status', choices=STATUSES)
    THEMES = (
        (1, 'Finance'),
        (2, 'IT'),
        (3, 'Develop'),
        (4, 'Building'),
    )
    theme = models.IntegerField(verbose_name='Theme', choices=THEMES)
    icon = models.ImageField(upload_to = user_directory_path, blank=True)

    def __str__(self):
        return self.name

serializers.py

from rest_framework import serializers
from .models import Company


class CompanySerializer(serializers.ModelSerializer):
    class Meta:
        model = Company
        fields = '__all__'

urls.py

from rest_framework import routers
from .api import CompanyViewSet

router = routers.DefaultRouter()
router.register('api/company', CompanyViewSet, 'company')

urlpatterns = router.urls

views.py

from django.shortcuts import render

# Create your views here.

api.py

from .models import Company
from rest_framework import viewsets, permissions
from .serializers import CompanySerializer


class CompanyViewSet(viewsets.ModelViewSet):
    queryset = Company.objects.all()
    permission_classes = [
        permissions.AllowAny
    ]
    serializer_class = CompanySerializer

如何通过指定列值获得条件结果。例如通过user_id和在user_members_id中,如果可能,受令牌限制

4

1 回答 1

2

您可以使用DRFSearchFilter

from rest_framework.filters import SearchFilter


class CompanyViewSet(viewsets.ModelViewSet):
    queryset = Company.objects.all()
    permission_classes = [
        permissions.AllowAny
    ]
    serializer_class = CompanySerializer

    filter_backends = (SearchFilter,)
    search_fields = ['username', 'email']

search要在您的 API 中搜索,请使用查询参数传递您的搜索关键字。

/path/to/end-point/?search=russell
于 2020-07-15T08:57:21.523 回答