Get only one filed from a nested serializer - django

Her it is my django serializer:
class ShopSerializer(serializers.ModelSerializer):
rest = RestSerializer(many=True)
class Meta:
model = RestaurantLike
fields = ('id', 'created', 'updated', 'rest')
This will wrap whole RestSerializer inside ShopSerializer on response.
How can I get only one or two fields from RestSerializer instead of having all the fields inside ShopSerializer?
Get only two field of RestSerializer instead of whole RestSerializer

If you want to have limited amount of fields from RestSerializer, then you can simply limit it in the fields:
class RestSerializer(serializers.ModelSerializer):
class Meta:
model = Restaurant
fields = ('id', 'name', ...)
If you want just want field, lets say the primary key or Slug, then you can use PrimaryKeyRelatedField or SlugRelatedField for that. For example:
class ShopSerializer(serializers.ModelSerializer):
rest = serializers.SlugRelatedField(
many=True,
read_only=True,
slug_field='name'
)
class Meta:
model = RestaurantLike
fields = ('id', 'created', 'updated', 'rest')

Related

Django Rest Framework -Serializer inside serializer using same instance

So, I have a weird legacy issue where I have one model "Data", and for serialization purposes I need to restructure the fields.
class Data(models.Model):
id ...
field_a
field_b
field_c
date
Then I have the serializers:
class DataInfoSerializer(ModelSerializer):
class Meta:
model = Data
fields = ['field_a', 'field_b', 'field_c']
class DataSerializer(ModelSerializer):
data_info = DataInfoSerializer(required=False, read_only=True)
class Meta:
model = Data
fields = ['id', 'date', 'data_info']
Now I somehow have to get DRF to use the same instance of Data that is passed into the "DataSerializer" to render the DataInfoSerializer.
Any ideas how to achieve this? Or a better way.
Use source='*' to pass the entire object to a field, including nested serializers. Docs
class DataSerializer(ModelSerializer):
data_info = DataInfoSerializer(required=False, read_only=True, source='*')
class Meta:
model = Data
fields = ['id', 'date', 'data_info']

How to Serialize different nested Serializes when the order is not allowing so

so I'm new to Django and I'm creating an API using djangorestframework
When creating the serializers I encountered a problem that I can't find a way to go around it.
I have 2 models, Site and Article
The site can have many articles
an article can have one site
I did the relationship in the models and everything looks fine.
When tried to serialize the information I started with the SiteSerializer which had a line to get the ArticleSerializer and had a related name of 'articles' (also the name of the variable) and it worked
But when trying to serialize the SiteSerializer inside the ArticleSerializer with the same way it cannot be done because the order of the classes, it cannot reference to it when it's yet to be created
CODE:
class ArticleSerializer(serializers.ModelSerializer):
site = SiteSerializer(many=false)
class Meta:
model = Article
fields = ('id', 'title', 'url', 'summary', 'img', "published_date", 'site')
class SiteSerializer(serializers.ModelSerializer):
articles = ArticleSerializer(many=True)
class Meta:
model = Site
fields = ('id', 'name', 'url', 'articles')
I can't reference to SiteSerializer when it's below, but it will be the opposite if I switch them up.
What can I do in this situation, is there another way to serialize different models with many to one or many to many relationships?
You are going to have an infinite loop (Site > Articles > Site > Article, ...).
You can create 4 serializers :
class NestedArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ('id', 'title', 'url', 'summary', 'img', "published_date", 'site')
class SiteSerializer(serializers.ModelSerializer):
articles = NestedArticleSerializer(many=True)
class Meta:
model = Site
fields = ('id', 'name', 'url', 'articles')
class NestedSiteSerializer(serializers.ModelSerializer):
class Meta:
model = Site
fields = ('id', 'name', 'url')
class ArticleSerializer(serializers.ModelSerializer):
site = NestedSiteSerializer()
class Meta:
model = Article
fields = ('id', 'title', 'url', 'summary', 'img', "published_date", 'site')

django-rest ModelSerializer select fields to display in nested relationship

I'm going to reference the django-rest-framework API example on this. Lets say we have two serializers defined as below.
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ['order', 'title', 'duration']
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True, read_only=True)
class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
Now if i do a GET request and retrieve an Album instance, it will return me a response with a list of Track instances inside it where each instance contains all the fields of Track. Is there a way to return only a selected subset of the fields in the Track model? For example to only return the title and duration field to the client but not the 'order' field.
You can make a specific TrackSerializer for your Album, like:
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ['order', 'title', 'duration']
class TrackForAlbumSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ['title', 'duration']
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackForAlbumSerializer(many=True, read_only=True)
class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
You do not have to define a single serializer per model, you can define multiple serializers you each use for a dedicated task.

Restricted set of nested fields in a django REST framework ModelSerializer

Consider the following serializer
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('id', 'account')
depth = 1
The field account refers to a ForeignKey in MyModel and I want to expose some of the Account fields with this serializer but not all of them.
How do I specify that only account.name and account.email should be serialized?
You can do this by creating your own serializer to use as the nested serializer.
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('name', 'email', )
You are better off with creating specialized serializers instead of relying on Django REST Framework to create them for you. By default, serializers that are automatically created contain all fields defined on the model.
class MyModelSerializer(serializers.ModelSerializer):
account = AccountSerializer()
class Meta:
model = MyModel
fields = ('id', 'account', )
You can find out more about nested serializers in the Django REST Framework documentation.

Adding more fields or linking user to person

Hello I'm trying to learn django and django-restful-framework.
I was wondering can I add more fields to User(contrib.auth) like so
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'firstName', 'lastName', 'ssn', 'email',
'phone', 'jobTitle','image', 'isActive','groups')
This gives me error on firstName. I also tried to tie this with person, but no luck either
class PersonSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
class Meta:
model = Person
fields = ('url', 'firstName', 'lastName', 'ssn', 'owner')
class UserSerializer(serializers.HyperlinkedModelSerializer):
persons = serializers.ManyHyperlinkedRelatedField(view_name='person-detail')
class Meta:
model = User
fields = ('url', 'username', 'persons')
I'm trying to make this so that the user can register with more information.
I suggest you head to the Django docs on extending and/or replacing the existing user model.
Once you've got what you want as the model level see if you can serialize that to your needs. (If not post again.)
The field names are lowercase with underscores. E.g it should be first_name and not firstName.