is there any way to show only a list of fields or excluding some of them when using django-rest-framework?
Here's my app/views.py:
from rest_framework.generics import ListAPIView
from .models import PhpbbUsers
class UsersReadView(ListAPIView):
model = PhpbbUsers
Obiously there are some user information that I don't want to show to everyone. How could I do?
Solution code
from rest_framework import generics, serializers
from .models import PhpbbUsers
class UsersSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = PhpbbUsers
fields = ('user_id', 'username', 'user_avatar')
class UsersReadView(generics.ListAPIView):
model = PhpbbUsers
serializer_class = UsersSerializer
Set the serializer_class attribute on the view.
See the quickstart for a good example: http://django-rest-framework.org/tutorial/quickstart.html
Related
I Trying get list of objects using DRF, But Getting Error like "missing "Meta.model attribute"
Serialzers.py
from rest_framework import serializers
from .models import Car
class CarSerializer(serializers.ModelSerializer):
class Meta:
model: Car
fields=['brand_name','model_name','car_color']
Views.py Code Below:
from app2.serializers import CarSerializer
from rest_framework import generics
class BrandList(generics.ListCreateAPIView):
queryset = Brand.objects.all()
serializer_class = CarSerializer
URLS.py:
from app2.views import ,BrandList
path("BrandList/", BrandList.as_view(), name="BrandList"),
Please someone get out from this
Try models = instead of : in serializers.py
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields=['brand_name','model_name','car_color']
I am using Django with Django Rest Framework for serializers.
I have the following situation.
In file models.py:
from django.db.models import Manager, Model, CharField
from .serializers import MyModelSerializer
class MyModelManager(Manager):
serializer_class = MyModelSerializer
class MyModel(Model):
name = CharField(max_length=64)
objects = MyModelManager()
In file serializers.py:
from rest_framework.serializers import ModelSerializer
from models import MyModel
class MyModelSerializer(ModelSerializer):
class Meta:
model = MyModel
fields = ('name',)
However, this leads to an import cycle, since both files try to import each other. I could prevent this by making a local import:
class MyModelManager(Manager):
#property
def serializer_class(self):
from ow_articlecode.import_cycle_serializers import MyModelSerializer
return MyModelSerializer
However, this feels like a hack. What would be a proper solution to break this import cycle?
A Manager [Django-doc], has no serializer_class field. In fact a manager does not know anything about serialization. A manager is used to filter, create, etc. objects.
Your models.py thus should look like:
# app/models.py
from django.db.models import Manager, Model, CharField
class MyModelManager(Manager):
# no serializer_class
pass
class MyModel(Model):
name = CharField(max_length=64)
The idea of Models is that this defines your business logic, not the serialization, form, view, template logic.
I am using Django version 2.1 and I am testing my project using Postman.
This is my views.py file :-
from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView
from rest_framework.permissions import AllowAny
# Add + List
# Retrieve Update Destroy
# List: Pagination
class ShowAddaView(ListCreateAPIView):
from .serializers import AddAddaSerializer
from .models import Adda
permission_classes = (AllowAny, )
serializer_class = AddAddaSerializer
queryset = Adda.objects.all()
class RetrieveAddaView(RetrieveUpdateDestroyAPIView):
from .serializers import AddAddaSerializer
from .models import Adda
permission_classes = (AllowAny,)
serializer_class = AddAddaSerializer
queryset = Adda.objects.all()
I am applying GET and POST method in postman. My serializer file looks like this :
class AddAddaSerializer(serializers.ModelSerializer):
class Meta:
from .models import Adda
model = Adda
fields = '__all__'
class UpdateAddaSerializer(serializers.ModelSerializer):
mobile = serializers.CharField(required=False)
class Meta:
from .models import Adda
model = Adda
fields = '__all__'
Now I need to access my data using the GET method in Postman with pagination.
Can anyone tell me what changes I need to do to achieve it.
Add this settings to your settings.py file,
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10 # Change this value according to your need
}
or You could add pagination class in View level by pagination_class as
from rest_framework.pagination import PageNumberPagination
class ShowAddaView(ListCreateAPIView):
# your code
pagination_class = PageNumberPagination
class RetrieveAddaView(RetrieveUpdateDestroyAPIView):
# your code
pagination_class = PageNumberPagination
For more details, refer Pagination in DRF
i'm new to django. The version i'm using is 1.11.2
I have a a schema like this.
There are many "designs" and each design can have any number of "patterns".
my design model is like below
from django.db import models
from products.models import Product
class Design(models.Model):
name = models.CharField(max_length=200)
product_id = models.ForeignKey(Product, on_delete=models.CASCADE)
price = models.CharField(max_length=200)
def __str__(self):
return self.name
My design serializer is like below
from rest_framework import serializers
from .models import Design
from rest_framework import serializers
from patterns.models import Pattern
class DesignsSerializer(serializers.ModelSerializer):
patterns = DesignPatternSerializer(read_only=True, many=True)
class Meta:
depth = 1
model = Design
fields = ('id','name','patterns')
read_only_fields = ('id','name','patterns')
The view for designs is as below
from django.shortcuts import render
from .models import Design
from .serializers import DesignsSerializer
from rest_framework import generics, filters
# Create your views here.
class ListDesignsByProducId(generics.ListCreateAPIView):
serializer_class = DesignsSerializer
def get_queryset(self):
return Design.objects.filter(product_id__exact = self.kwargs.get('product_id'))
My pattern model is like below.
from django.db import models
from datetime import date
from designs.models import Design
class Pattern(models.Model):
design_id = models.ManyToManyField(Design)
name = models.CharField(max_length=200)
def __str__(self):
return self.name
My pattern serializer is as below
from rest_framework import serializers
from .models import Pattern
class PatternSerializer(serializers.ModelSerializer):
class Meta:
depth = 1
model = Pattern
fields = ('id','design_id','name')
read_only_fields =('id','design_id','name')
Right now the api would return the details of the designs and it's associated products.
I would also like to get an array of patterns associated with the design.
In your DesignsSerializer you referred to the patterns by the name patterns without defining it in your models.
From the Django REST Framework documentation:
You'll normally want to ensure that you've set an appropriate
related_name argument on the relationship, that you can use as the
field name.
In your Pattern model:
class Pattern(models.Model):
design_id = models.ManyToManyField(Design, related_name='patterns')
...
http://127.0.0.1:8000/?words=anger
and I want to add 'anger' to the field serializer dynamically.
from .models import Synonym
from rest_framework import serializers
class SynonymSerializer(serializers.ModelSerializer):
class Meta:
model = Synonym
fields = ('word',)