Conditionally nest Django serializers - django

So, I have a foreign key to my User model in many of my models. Now, the serializers for these models are nested, in that they include the entire user object rather than just the id. I have done so as shown bellow:
class BadgeSerializer(serializers.ModelSerializer):
user = UserSerializer(read_only=True)
class Meta:
model = Badge
fields = '__all__'
It works as expected. However, I seldom find myself in a situation where I want just the id. I was wondering what is the best way to conditionally nest my BadgeSerializer...

Now, the best solution I can think of is to have a non-nested BadgeSerializer, which includes only the user id. And then have a NestedBadgeSerializer (extending BadgeSerializer) which does nest the User model and include the entire user object.
class BadgeSerializer(serializers.ModelSerializer):
class Meta:
model = Badge
fields = '__all__'
class NestedBadgeSerializer(BadgeSerializer):
user = UserSerializer(read_only=True)
class Meta:
model = Badge
fields = '__all__'
I am NOT sure if that's the proper way though.

Related

Need to fetch two specific field values from one model to another seperately in django API rest framework

model 1
class Users(models.Model):
employee_name = models.CharField(max_length=50)
dob=models.DateField(max_length=8)
email=models.EmailField(max_length=254,default=None)
pancard=models.CharField(max_length=25,default=None)
aadhar=models.CharField(max_length=20,default=None)
personal_email_id=models.EmailField(max_length=254,default=None)
phone = PhoneField(blank=True)
emergency_contact_no=models.IntegerField(default=None)
emergency_contact_name=models.CharField(max_length=100,null=True)
relation=models.CharField(max_length=25,default=None)
blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True)
desingnation=models.ForeignKey(Designation,on_delete=CASCADE,related_name="desingnation")
billable_and_non_billable=models.CharField(max_length=25,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable')
joining_date=models.DateField(max_length=15,null=True)
relieving_date=models.DateField(max_length=15,null=True)
def __str__(self):
return self.employee_name
model 2
class Consolidated(models.Model):
emp_name=models.ForeignKey(Users,on_delete=CASCADE)
proj_name=models.ForeignKey(Project,on_delete=CASCADE)
custom_name=models.ForeignKey(Client,on_delete=CASCADE)
Cons_date=models.ForeignKey(Add_Timelog,on_delete=CASCADE)
bill_no_bill=models.ForeignKey(Users,on_delete=CASCADE,related_name="billable_and_non_billable+")
def __str__(self):
return str(self.emp_name)
Serializers
class UserSerializers(serializers.ModelSerializer):
class Meta:
model= Users
fields = '__all__'
class Consolidated_serializers(serializers.ModelSerializer):
class Meta:
model=Consolidated
fields= '__all__'
Viewsets
class UserViewset(viewsets.ModelViewSet):
permission_classes=(permissions.IsAdminUser,)
queryset=models.Users.objects.all()
serializer_class=serializers.UserSerializers
class Consolidated_ViewSet(viewsets.ModelViewSet):
permission_classes=(permissions.IsAdminUser,)
queryset=models.Consolidated.objects.all()
serializer_class=serializers.Consolidated_serializers
Actually I was stucked in the middle, as I need to take the values from 'billable_and_non_billable' field from the Users model and display those values under Consolidated model bill_no_bill field. With the above code I can only take the employee_name values from the Users model to the emp_name of Consolidated model and the same value is getting displayed in the bill_no_bill field. Please help me find any ways for this problem as I am new to this Django. Basically its needs to be a API which operates GET method.
You are getting same value because you are using Foreign Key to the user model for both emp_name and bill_no_bill. Foreign keys are used for many to one relations between models.
See: https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/
So your Consolidated Model should be:
class Consolidated(models.Model):
employee=models.ForeignKey(Users,on_delete=CASCADE)
project=models.ForeignKey(Project,on_delete=CASCADE)
custom_name=models.ForeignKey(Client,on_delete=CASCADE)
cons_date=models.ForeignKey(Add_Timelog,on_delete=CASCADE)
To get the values of these fields you can use Nested Objects Representation in DRF serializers.
So the consolidated serializer becomes:
class ConsolidatedSerializer(serializers.ModelSerializer):
employee = UserSerializer()
class Meta:
model = Consolidated
fields = ['employee', 'project', 'custom', 'date']
The bill_no_bill field would be part of the returned object in viewset.
Alternatively you can override the to_representation method of serializer or SerializerMethodField

Django equivalent of ASP.NET Parameter Binding or Ruby on Rails Action Controller Parameters

I'm wondering what's mentioned in the title. This are links to the examples mentioned, regarding other techs:
ASP.NET Parameter Binding
Ruby on Rails Action Controller
Parameters
Currently I'm building an API using DRF and using custom code in views or serializers validate methods to validate parameters, like this:
class AnimalWriteSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = '__all__'
def validate_dicose_category(self, value):
raise serializers.ValidationError('Dicose Category cannot be set manually.')
Is there a better way?
Since in your example you are telling the serializer to support __all__ fields, then you need to disable updating that one manually.
You probably mean to use use exclude as in the example below, which will simply remove the field from "all". The primary difference between exclude and using read_only is that the output will include the dicose_category.
Use the exclude= to exclude this field. This is the opposite of fields=, and you can only use one at a time.
class AnimalWriteSerializer(serializers.ModelSerializer):
dicose_category = serializers.CharField(read_only=True)
class Meta:
model = Animal
exclude = ["dicose_category"]
You can declare the field as read only (directly or using extra kwarg). You can't write it but it will include be in the output. I'm not sure why you would want to do this, but it can be helpful if you are using the return data for something and need it there.
class AnimalWriteSerializer(serializers.ModelSerializer):
dicose_category = serializers.CharField(read_only=True)
class Meta:
model = Animal
fields = "__all__"
# or declare an extra_kwarg which does the same thing:
class AnimalWriteSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = "__all__"
extra_kwargs = {
"dicose_category": { "read_only": True }
}
And lastly, I strongly suggest listing all the fields you intended to be updated directly, rather than using __all__ or exclude=.
New fields added to the model are not automatically updateable
All updateable fields are explicitly and clearly listed
Unit tests can now be explicit, and the output format is consistent
class AnimalWriteSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = [
"name",
"mission",
"favorite_color",
]

Expected a dictionary, but got str Django Rest Framework

Right now I am creating a user department with a list of users that are a foreign key back to the main user model. I had this working yesterday, but for some reason I screwed it up. I imagine it has something to do with the serializers. I want to be able to post a list of users in this format
['jack', 'tom']
However, even using the raw data api this is not allowing me to do this. Here is my code:
Serializers:
class DepartmentSerializer(serializers.ModelSerializer):
user_department = UserSerializer(many=True)
class Meta:
model = Departments
fields = '__all__'
class DepartmentUpdateSerializer(serializers.ModelSerializer):
user_department = UserSerializer(many=True)
class Meta:
model = Departments
fields = ['department_name', 'department_head', 'user_department']
I swear yesterday it was allowing me to select from a list of users in the api. I could also post and it would work from the front end. However, now whenever I create a department it's expecting a dictionary, which I am not trying to pass.
Dudes, for whatever reason, removing () after the UserSerializer fixed it. If anyone can explain why that would be even better!
class DepartmentSerializer(serializers.ModelSerializer):
user_department = UserSerializer
class Meta:
model = Departments
fields =['department_name', 'department_head', 'user_department']
class DepartmentUpdateSerializer(serializers.ModelSerializer):
user_department = UserSerializer
class Meta:
model = Departments
fields = ['department_name', 'department_head', 'user_department']
When you use the nested serializer you need to add the nested serializer field (user_department in your case) to the fields too, as you can see you used
fields = '__all__'
which does not include your nested serializer field, you need to manually add that to the meta fields

Django REST ModelSerializer --- General Question

I am working through a tutorial that includes the building of an articles app. I have an Article model that I am serializing and I am curious about why I need to explicitly set certain fields when using a ModelSerializer.
Here is my model:
from django.db import models
from core.models import TimestampedModel
class Article(TimestampedModel):
slug = models.SlugField(db_index=True, max_length=255, unique=True)
title = models.CharField(db_index=True, max_length=255)
description = models.TextField()
body = models.TextField()
author = models.ForeignKey('profiles.Profile', on_delete=models.CASCADE, related_name='articles')
def __str__(self):
return self.title
Pretty standard stuff. Next step is to serialize the model data in my serializers.py file:
class ArticleSerializer(serializers.ModelSerializer):
author = ProfileSerializer(read_only=True) # Three fields from the Profile app
description = serializers.CharField(required=False)
slug = serializers.SlugField(required=False)
class Meta:
model = Article
fields = (
'author',
'body',
'createdAt',
'description',
'slug',
'title',
'updatedAt',
)
Specifically, why do I need to explicitly state the author, description, and slug fields if I am using serializers.ModelSerializer and pulling those fields in from my model in my class Meta: below?
Thanks!
In the Django-Rest-Framework documentation, drf-docs/model_serializer/specifying-which-fields-to-include it says:
If you only want a subset of the default fields to be used in a model serializer, you can do so using fields or exclude options, just as you would with a ModelForm. It is strongly recommended that you explicitly set all fields that should be serialized using the fields attribute. This will make it less likely to result in unintentionally exposing data when your models change.
Therefore by using fields = in the Serializer META, you can specify just the needed fields, and not returning vital fields like id, or exessive information like updated and created timestamps.
You can also instead of using fields, use exclude, which again takes in a tuple, but just excludes the fields you don't want.
These are especially useful when your database table contains a lot of information, returning all this information, especially if it is listed, can result in large return JSON's, where the frontend may only use a small percentage of the sent data.
DRF has designed their framework like this to specifically combat these problems.
In my opinion, we should define field in serializer for:
Your api use serializer don't need all data of your models. Then you can limit field can get by serializer. It faster if you have so much data.
You dont want public all field of your model. Example like id
Custom field in serializer like serializers.SerializerMethodField() must define in fields for work
Finally, iF you dont want, you can define serializer without define fields. Its will work normally

Update three-level nested django model using serializer

I am trying to update one of my models (which is a nested model - three level actually as you can see below) and I am getting the following error:
AssertionError: The .update() method does not support writable nestedfields by default. Write an explicit .update() method for serializer SystemSettingsSerializer, or set read_only=True on nested serializer fields.
All day I have been reading about nested models and nested serializers, trying to add update and create methods setting fields as read_only=True but no matter what I did, it just didn't work :( :(
These are my models:
class SystemSettings(models.Model):
# ... some fields
class Components(models.Model):
settings = models.ForeignKey(SystemSettings, related_name="Components")
class SysComponent(models.Model):
class Meta:
abstarct = True
index = models.PositiveIntegerField(primery_key=True)
is_active = models.BooleanField(default=False)
component = NotImplemented
class Foo(SysComponent):
component = models.ForeignKey(Components, related_name="Foo")
class Bar(SysComponent):
component = models.ForeignKey(Components, related_name="Bar")
task_id = models.PositiveIntegerField(default=0)
and serializers:
class SystemSettingsSerializer(ModelSerializer):
Components = ComponentsSerializer(many=True)
class Meta:
model = SystemSettings
fields = [# some fields,
Components]
class ComponentsSerializer(ModelSerializer):
Foo = FooSerializer(many=True)
Bar = BarSerializer(many=True)
class Meta:
model = Components
fields = ['Foo',
'Bar']
class FooSerializer(ModelSerializer):
class Meta:
model = Foo
class BarSerializer(ModelSerializer):
class Meta:
model = Bar
My logic is the following:
I am fetching the SystemSettings via GET and display it in a form.
The user changes it as much as he want and by clicking submit I send it back via PUT.
As I said I am getting the error above after clicking submit.
Any help would be appreciated.
EDIT: I am using django 1.7.8 by the way