Firstly I want to say I'm a newbie to Django.
I was wondering if is it possible to create a non-ModelSerializer which serialize existant model based serializers ?
In serializers.py, I already have this :
class MapSerializer(serializers.ModelSerializer):
class Meta:
model = Map
fields = ('id', 'name')
class GrenadeSerializer(serializers.ModelSerializer):
class Meta:
model = Grenade
fields = ('id', 'name')
I want here a new serializer which allows to display a JSON like that :
{
"maps": {
"map": [
{
"id": "1",
"name": "dust2"
},
{
"id": "2",
"name": "inferno"
}
]
},
"grenades": {
"grenade": [
{
"id": "1",
"name": "flashbang"
},
{
"id": "2",
"name": "smoke"
}
]
}}
I need something like this, even if I know the following structure isn't correct :
class MyNewSerializer(serializers.ModelSerializer):
maps = MapSerializer(many=True)
grenades = GrenadeSerializer(many=True)
class Meta:
field = ('maps', 'grenades')
Thanks in advance !
Related
I am building an API using django rest-framwork.
this is my data,
[
{
"id": 24,
"name": ""
},
{
"id": 45,
"name": "ADB"
},
{
"id": 2,
"name": "Agriculture"
},
{
"id": 27,
"name": "Category external workforce, professional and business services"
}]
it works fine if I provide a single item for the filter operation. like this.
http://127.0.0.1:8000/op-api/sec/?name=Agriculture
it returns me empty if I provide more then one item for the filtering purpose.
http://127.0.0.1:8000/op-api/sec/?name=Agriculture,ADB
but I want it should return data like this.
[
{
"id": 45,
"name": "ADB"
},
{
"id": 2,
"name": "Agriculture"
}
]
here is my code for the API
class sec_ViewSet(viewsets.ModelViewSet):
http_method_names = ['get']
serializer_class = sector_Serializer
filter_backends = [DjangoFilterBackend , SearchFilter , OrderingFilter]
filterset_fields = ['name',]
search_fields = ['name',]
def get_queryset(self) :
all_sec = Sector.objects.all()
return all_sec
class sector_Serializer(serializers.ModelSerializer) :
class Meta :
model = Sector
fields = ['id' , 'name']
how can I update it so that it works fine.
I'm trying to get my Product kind as what I declared It's name, instead I get number. Let me be more clear:
This below is my Product Kinds;
PRODUCT_KINDS = (
("1","Electronic"),
("2","Furniture"),
("3", "Bedroom"),
("4","Dining")
)
And this image below is my django-admin panel which everything seems perfect because I can get every single of my kinds.
However, when I try to get this data from api/products url I get this data
[
{
"image": null,
"name": "Headphones",
"kind": "1",
"price": 250.99,
"description": "No description for this item.",
"is_featured": true
},
{
"image": null,
"name": "Watch",
"kind": "3",
"price": 12.5,
"description": "No description for this item.",
"is_featured": true
},
{
"image": null,
"name": "T-shirt",
"kind": "2",
"price": 12.99,
"description": "No description for this item.",
"is_featured": true
},
{
"image": null,
"name": "Ali Ziya ÇEVİK",
"kind": "1",
"price": 1212.0,
"description": "No description for this item.",
"is_featured": false
}
]
as you can see In my django-admin panel I get the name of kind but In the API I get It's index.
This below is my serializer:
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
#kind = serializers.CharField(source = 'kind')
#print(kind)
class Meta:
model = Product
fields = ['image', 'name', 'kind',
'price', 'description', 'is_featured']
You could set source on value from Model.get_FOO_display() method
kind = serializers.CharField(source = 'get_kind_display')
You can try this use fields source with get_FOO_display :
https://docs.djangoproject.com/en/1.8/ref/models/instances/#django.db.models.Model.get_FOO_display
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
kind = serializers.CharField(source='get_kind_display')
class Meta(object):
model = Product
fields = ('image', 'name', 'kind','price', 'description', 'is_featured')
I've started learning how to use the Django REST Framework along with React and I have a quick question. I made a form and use CreateAPIView and UpdateAPIView to create/update items, respectively. But how do I get the contents to populate my <select> field if the list comes from a variable in one of my models?
from model_utils import Choices
class Author(models.Model):
GENDER = Choices('male', 'female', "I don't know really") # How do I get this?
gender = models.CharField(max_length=10, choices=GENDER)
What will the serializer and views for Author.GENDER look like since it's not a model?
At the moment, this is what I have for now.
Django (nothing out of the ordinary here, I think.).
# Serializer.
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = ('id', 'gender')
# View
class AuthorUpdateView(UpdateAPIView):
queryset = Author.objects.filter(deleted_at__isnull=True)
serializer_class = AuthorSerializer
React.
componentDidMount() {
const pk = this.props.match.params.pk
axios.get(`http://localhost:8000/api/authors/${pk}`)
.then(response => {
const pk = response.data.id
const gender = response.data.gender
this.setState({gender})
})
.catch(err => console.log(err))
}
I'm open to any direction or concept you might have when using DRF so I can also learn from how you would do it.
Use viewset to combine the logic for a set of your related views (list, create, update)
class AuthorViewSet(ModelViewSet):
queryset = Author.objects.filter(deleted_at__isnull=True)
serializer_class = AuthorSerializer
Make a OPTIONS request to get the metadata for your resource, including the list of valid choices of gender field
Request
OPTIONS /api/authors/
Response
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"name": "Author List",
"parses": [
"application/json",
"application/x-www-form-urlencoded",
"multipart/form-data"
],
"actions": {
"POST": {
"id": {
"type": "integer",
"required": false,
"read_only": true,
"label": "Id"
},
"gender": {
"type": "choice",
"required": true,
"read_only": false,
"label": "Gender",
"choices": [
{
"value": "male",
"display_name": "male"
},
{
"value": "female",
"display_name": "female"
},
{
"value": "I don't know really",
"display_name": "I don't know really"
}
]
}
}
}
}
I have 2 model classes:
class CustomUser(AbstractUser):
username = models.CharField(max_length=30, unique=True)
tags = models.ManyToManyField('events.Tag', related_name='user_tag', blank=True)
class Tag(models.Model):
name = models.CharField(unique=True, max_length=50)
And serializers:
class UserSerializer(serializers.ModelSerializer):
tags = TagSerializer(many=True)
class Meta:
...
class TagSerializer(serializers.ModelSerializer):
class Meta:
lookup_field = 'name'
model = Tag
fields = ('id', 'name')
When I do a get query I get something like this:
"data": {
"type": "CustomUser",
"id": "6",
"attributes": {
"username": "mercer",
},
"relationships": {
"tags": {
"data": [
{
"type": "Tag",
"id": "1"
}
]
},
}
}
What I want is to get Tag 'name' field in user representation:
"type": "Tag",
"id": "1",
"name":"name"
And I want to make patch query for adding tag to user.
I can use SerializerMethodField(), but this way I will not able to add tags
The problem was with settings of rest framework. I wrote there custom json render classes and recived this form of output. Now i removed it and everything is fine.
I'm rather new to Django Rest Framework and I'm trying to use DRF to to serialize a list of (related) objects.
I have the following models:
class Answer(models.Model):
value = models.CharField(max_length=128)
class User(models.Model):
name = models.CharField(max_length=128)
age = models.PositiveIntegerField()
class UserAnswer(models.Model):
user = models.ForeignKey(User)
answer = models.ForeignKey(Answer)
And the result I'm trying to get is in this form:
[
{
"name": "myName1",
"answers": [
{
"value": "myFirstAnswer"
},
{
"value": "mySecondAnswer"
},
{
"value": "myThirdAnswer"
},
]
},
{
"name": "myName2",
"answers": [
{
"value": "myFirstAnswer"
},
{
"value": "mySecondAnswer"
},
{
"value": "myThirdAnswer"
},
]
}
]
I'm trying to do it this way now:
class UserAnswerSerializer(serializers.ModelSerializer):
answers = AllUserAnswersSerializer(many=True, read_only=True)
class Meta:
model = User
fields = ('name', 'answers')
But then I get the following result:
[
{
"name": "myName1"
},
{
"name": "myName2"
}
]
And when I try to do it this way:
class UserAnswerSerializer(serializers.ModelSerializer):
answers = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = User
fields = ('name', 'answers')
Then i get the following result (an example again):
[
{
"name": "myName1",
"answers": [
1,
2,
3
]
},
{
"name": "myName2",
"answers": [
4,
5,
6
]
}
]
I'm having a hard time making this work, hope someone can show me how to convert the Primary Key's to actual objects!
Thanks!
Remove the explicit definition of the answers field in your serializer and add depth=1. It should look like this:
class UserAnswerSerializer(serializers.ModelSerializer):
class Meta:
depth = 1
model = User
fields = ('name', 'answers')
Info about depth: http://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization