MrOldSir
MrOldSir

Reputation: 726

django rest fraemwork. Filtering model according data in relation models

I have a some models like:

class MainModel(TimeStampedModel):
    model_name = models.CharField(_("model_name"), max_length=240)        
    model_price = models.DecimalField(_("model_price"), max_digits=8)

class ModelAdditionalData_1(TimeStampedModel):
    model_id = models.OneToOneField(
        Model,
        verbose_name=_('related model'),
        on_delete=models.CASCADE,
        related_name='model_water_flow_data1',
        related_query_name='model_water_flow_data1'
    )
    model_param_1 = models.models.DecimalField(_("model_param_1"), max_digits=8)

class ModelAdditionalData_2(TimeStampedModel):
    model_id = models.OneToOneField(
        Model,
        verbose_name=_('related model'),
        on_delete=models.CASCADE,
        related_name='model_water_flow_data2',
        related_query_name='model_water_flow_data2'
    )
    model_param_2 = models.models.DecimalField(_("model_param_2"), max_digits=8)

urls.py

details_router = SimpleRouter()
details_router.register('models', DetailViewSet, 'models')


urlpatterns = details_router.urls

views.py

DETAIL_FILTER_PARAMETERS = [
openapi.Parameter(
    'model_param_1',
    openapi.IN_QUERY,
    type=openapi.TYPE_STRING,
    format=openapi.FORMAT_DECIMAL
),
openapi.Parameter(
    'model_param_2',
    openapi.IN_QUERY,
    type=openapi.TYPE_STRING,
    format=openapi.FORMAT_DECIMAL
)
]

@method_decorator(name='list', decorator=swagger_auto_schema(
manual_parameters=DETAIL_FILTER_PARAMETERS))
class ModelsViewSet(ReadOnlyModelViewSet, GenericViewSet):
    serializer_class = ModelsSerializer

    def list(self, request, *args, **kwargs):
        ....

Here is request with params to filter:

curl -X GET "http://localhost:8000/api/v1/models/?model_param_1=1&model_param_2=2" -H  "accept: application/json"

How i can filter model Model according to data in relation models ModelAdditionalData_1 and ModelAdditionalData_2 with query params and return json only with records which corespond to filter?

Upvotes: 0

Views: 52

Answers (1)

ThomasGth
ThomasGth

Reputation: 870

With the Django ORM, you can filter objects based on the values of their relationships attributes

You can override the get_queryset() method of your viewset to filter against the parameters:

def get_queryset(self):
    model_param_1 = self.request.query_params.get('model_param_1')
    model_param_2 = self.request.query_params.get('model_param_2')
    
    filters = {}
    if model_param_1:
        filters['model_water_flow_data1__model_param_1'] = model_param_1
    if model_param_2:
        filters['model_water_flow_data2__model_param_2'] = model_param_2

    if filters:
        return MainModel.objects.filter(**filters)

    return MainModel.objects.all()

Upvotes: 1

Related Questions