0

How can I make a request for DRF, as if it would be like a request for SELECT by LIKE condition? Now they are displayed to me like this enter image description here but I want to output depending on the values in the columns user_id and user_members_id. I have this code

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

How get conditinaled result by specify column value. For example by user_id and is have in user_members_id and if possible, to be limited by token

David Amirkhanov
  • 43
  • 1
  • 1
  • 10

1 Answers1

2

You can use DRF's SearchFilter

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']

To search in your API, pass your search keyword using search query parameter.

/path/to/end-point/?search=russell
JPG
  • 82,442
  • 19
  • 127
  • 206
  • Okay. I added in filter **user_id** and i check the link https://crm.wsofter.ru:8000/api/company/?user_id=5, but not work ` filter_backends = (SearchFilter,) search_fields = ['user_id', 'user_members_id']` – David Amirkhanov Jul 15 '20 at 09:10
  • You should use **`search`** as the query parameter. (see the update) – JPG Jul 15 '20 at 09:19
  • I still do not understand how it works and why search is needed, if I want to do conditional selection from a database through API. It is not work for me, because in my case i select by columns type models.ForeignKey and ArrayField – David Amirkhanov Jul 15 '20 at 10:00
  • Search is implemented using **%LIKE%** in DRF. Also, what do you mean by a ***conditional selection***? – JPG Jul 15 '20 at 10:05
  • I have error ). For example, I do a search like this https://crm.wsofter.ru:8000/api/company/?search=5 if i want search user_id=5? But how a can set in URL params user_id and user_members_id? – David Amirkhanov Jul 15 '20 at 10:16
  • Ohh... Then I suggest you to configure [django-filter](https://django-filter.readthedocs.io/en/stable/) which has great flexibility in doing such things. – JPG Jul 15 '20 at 10:18