Disable read only fields in the response after posting the data - django

My model:
class NewsID(models.Model):
pass
class News(models.Model):
newsId=models.ForeignKey(NewsID,related_name = 'News', on_delete=models.CASCADE)
lang_code=models.CharField(max_length=2)
headline=models.CharField(max_length=100)
class DefaultLanguage(models.Model):
news_id = models.ForeignKey(NewsID,related_name = 'default', on_delete=models.CASCADE)
defaultLanguage_id = models.IntegerField(unique=True)
My serializer:
class NewsSerializer(QueryFieldsMixin,serializers.ModelSerializer):
class Meta:
model=News
fields=('lang_code','headline')
class DefaultLanguageSerializer(QueryFieldsMixin,serializers.ModelSerializer):
class Meta:
model = DefaultLanguage
fields = ('news_id ','defaultLanguage_id ')
read_only_fields = ['news_id ','defaultLanguage_id ']
class NewsIDSerializer(QueryFieldsMixin,serializers.ModelSerializer):
News = NewsSerializer(many=True)
default_language = serializers.CharField(max_length=2,write_only=True)
class Meta:
model = NewsID
fields = ('id','News','default_language')
I want the response as below after posting :
{
"id": 10,
"News": [
{
"lang_code": "en",
"headline": "Breaking news"
}
],
"default_language": "en"
}
Now my response looks as below:
{
"id": 10,
"News": [
{
"lang_code": "en",
"headline": "Breaking news"
}
]
}
Now my response is having news_id and defaultLanguage_id (read only fields) I don't want the response with read only fields after posting. How to achieve this using Django?

change your serializer from
class NewsIDSerializer(QueryFieldsMixin,serializers.ModelSerializer):
News = NewsSerializer(many=True)
default = DefaultLanguageSerializer(many=True,read_only=True)
default_language = serializers.CharField(max_length=2,write_only=True)
class Meta:
model = NewsID
fields = ('id','News','default','default_language')
To
class NewsIDSerializer(QueryFieldsMixin,serializers.ModelSerializer):
News = NewsSerializer(many=True)
default_language = serializers.CharField(max_length=2)
class Meta:
model = NewsID
fields = ('id','News','default_language')
It will work as you expected.

Related

django rest_framework how to display nested relationship

I'm trying to display foreign related fields like this example and it works
{
"reqid": 10,
"reqdate": "2022-12-05",
"reqdescription": "Aircon Not working",
"officerequestor": "OVCAA ",
"officeid": "PPD ",
"inspection": {
"insdate": "2022-12-06",
"diagnosis": "need to buy prism",
"inspector": "EMP-322 "
}
},
this is my serializers.py
class RequestAdditionDetailsSerializer(serializers.ModelSerializer):
class Meta:
model = Inspection
fields = ['insdate',
'diagnosis',
'inspector'
]
class RequestorSerializer(serializers.ModelSerializer):
inspection = RequestAdditionDetailsSerializer(read_only=True)
class Meta:
model = Request
fields = ['reqid',
'reqdate',
'reqdescription',
'officerequestor',
'officeid',
'inspection'
]
My question is can I do this the other way around like this
{
"inspectid": 5,
"reqid": "10",
"insdate": "2022-12-06",
"diagnosis": "need to buy prism",
"inspector": "EMP-322",
"isinspected": {
"reqdescription": "Aircon Not working",
"reqdate": "2022-12-05",
"officerequestor": "OVCAA"
}
},
this is what I've tried, tbh I don't think this will work is there a solution for this.
if no maybe i'll add additional columns on inspection like reqdescription,reqdate etc.. just to show them
class InspectionAdditionalDetailsViewSerializer(serializers.ModelSerializer):
class Meta:
model = Request
fields = ['reqdescription',
'reqdate',
'officerequestor'
]
class InspectionSerializer(serializers.ModelSerializer):
request_details = InspectionAdditionalDetailsViewSerializer(read_only=True)
class Meta:
model = Inspection
fields = ['inspectid',
'reqid',
'insdate',
'diagnosis',
'inspector',
'isinspected',
'request_details'
]
this is my models.py
class Inspection(models.Model):
inspectid = models.AutoField(primary_key=True)
reqid = models.OneToOneField('Request', models.DO_NOTHING, db_column='reqid', blank=True, null=True)
class Meta:
managed = False
db_table = 'inspection'
class Request(models.Model):
reqid = models.AutoField(primary_key=True)
class Meta:
managed = False
db_table = 'request'
You have defined the OneToOne field name reqid therefore you should use it as serializer key.
Noted that Django will add _id to the field so it will become reqid_id in your database, it's best to name it req or request only to refer to related object.
class InspectionAdditionalDetailsViewSerializer(serializers.ModelSerializer):
class Meta:
model = Request
fields = [
'reqdescription',
'reqdate',
'officerequestor',
]
class InspectionSerializer(serializers.ModelSerializer):
reqid = InspectionAdditionalDetailsViewSerializer(read_only=True)
class Meta:
model = Inspection
fields = [
'inspectid',
'reqid',
'insdate',
'diagnosis',
'inspector',
'isinspected',
]

Django nested Serializer filter to only one field, not all fields

I have two serializers like below. The output for the below snippet is Workers and with associated Ticket Counter details with all fields (ticket_counter,ticket_counter_name,worker). But I just need only one field that is ticket_counter_name.
class WorkerSerializer(serializers.ModelSerializer):
ticket_counter = WorkerToCounterSerializer(many=True, read_only=True)
class Meta:
model = User
fields = (
'username',
'ticket_counter',
)
class WorkerToCounterSerializer(serializers.ModelSerializer):
ticket_counter = SerializerMethodField()
ticket_counter_name = serializers.CharField(source='ticket_counter.ticket_counter_name')
class Meta:
model = WorkerToTicketCounter
list_serializer_class = FilteredListSerializer
fields = (
'ticket_counter',
'ticket_counter_name',
'worker',
)
def get_ticket_counter(self, obj):
return obj.ticket_counter.pk
class FilteredListSerializer(ListSerializer):
def to_representation(self, data):
data = data.filter(worker_to_ticket_counter_is_deleted=False)[:1]
return super(FilteredListSerializer, self).to_representation(data)
What above snippet outputs
{
"username": "xxxxxxxxxxx",
"ticket_counter": [
{
"ticket_counter": 7,
"ticket_counter_name": "Entrance Counter",
"worker": 4,
}
]
}
But What I want is
{
"username": "xxxxxxxxxxx",
"ticket_counter": "Entrance Counter"
}
I just need the name of the ticket_counter_name. In my case, there can't be two ticket_counters for a worker. Obviously, it gives only one ticket_counter. Is it possible?
EDIT: using string StringRelatedField
{
"username": "xxxxxxxxxxx",
"ticket_counter": [
"Entrance Counter",
"xxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxx"
]
}
EDIT: WorkerToTicketCounter Model
class WorkerToTicketCounter(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
ticket_counter = models.ForeignKey(TicketCounter, related_name="workers")
worker = models.ForeignKey(User, related_name='ticket_counter')
worker_to_ticket_counter_is_deleted = models.BooleanField(default=False)
If I'm understood correctly, you only need a SerializerMethodField to perform both filtering and string represantion.
class WorkerSerializer(serializers.ModelSerializer):
ticket_counter = serializers.SerializerMethodField(read_only=True)
def get_ticket_counter(self, user):
qs = user.ticket_counter.filter(worker_to_ticket_counter_is_deleted=False)
if qs.exists() and hasattr(qs.first().ticket_counter, 'ticket_counter_name'):
return qs.first().ticket_counter.ticket_counter_name
return None
class Meta:
model = User
fields = ('username', 'ticket_counter',)
You can use StringRelatedField:
class WorkerSerializer(serializers.ModelSerializer):
ticket_counter = StringRelatedField(many=True, read_only=True)
class Meta:
model = User
fields = (
'username',
'ticket_counter',
)
Note to use StringRelatedField you should add __str__ method to your WorkerToTicketCounter model:
class WorkerToTicketCounter:
...
def __str__(self):
return self.ticket_counter.ticket_counter_name

Get StringRelatedField along with PrimaryKeyRelatedField using Serializer in DRF

Sorry for this newbie question, but I simply cannot find my way reading the manual.
models
#Subject
class TemaPai(models.Model):
subject = models.TextField()
disciplines = models.ManyToManyField(Materia)
# order = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.subject
class Meta:
verbose_name_plural = "temas-pais (subjects)"
# Order and junction
class TemaPaiOrdem(models.Model):
subject = models.ForeignKey(TemaPai, on_delete=models.CASCADE)
discipline = models.ForeignKey(Materia, on_delete=models.CASCADE)
order = models.IntegerField()
def __str__(self):
var2 = self.subject.subject
var = self.discipline.discipline
return var2 + ' - ' + var
class Meta:
verbose_name_plural = "Temas-pais-ordem"
unique_together = ('subject', 'discipline')
serializers
class TemaPaiSerializer(serializers.ModelSerializer):
disciplines = serializers.PrimaryKeyRelatedField(many=True, queryset=Materia.objects.all())
class Meta:
model = TemaPai
fields = ('id', 'subject', 'url', 'disciplines')
class TemaPaiOrdemSerializer(serializers.ModelSerializer):
discipline = serializers.PrimaryKeyRelatedField(queryset=Materia.objects.all())
subject = serializers.PrimaryKeyRelatedField(queryset=TemaPai.objects.all())
class Meta:
model = TemaPaiOrdem
fields = ('id', 'subject','discipline', 'order')
Well, TemaPaiOrdemSerializer is giving me a list like this:
[
{
"id": 1,
"subject": 1,
"discipline": 1,
"order": 1
},
{
"id": 2,
"subject": 2,
"discipline": 1,
"order": 11
}
]
It is fine. But I want to retrieve the subject string representation (from TemaPai model) as well, as a read_only field. So my desired list would be something like:
[
{
"id": 1,
"subject": 1,
"subject_name": "Introduction",
"discipline": 1,
"order": 1
},
{
"id": 2,
"subject": 2,
"subject_name": "Advanced stuff",
"discipline": 1,
"order": 11
}
]
I am trying to use
subject_name = serializers.ReadOnlyField(source:'subject')
with no success. Any hint would be appreciated.
Use ,
subject_name = serializers.StringRelatedField(source='subject',read_only=True)
hence your serializer will be like,
class TemaPaiOrdemSerializer(serializers.ModelSerializer):
discipline = serializers.PrimaryKeyRelatedField(queryset=Materia.objects.all())
subject = serializers.PrimaryKeyRelatedField(queryset=TemaPai.objects.all())
subject_name = serializers.StringRelatedField(source='subject',read_only=True)
class Meta:
model = TemaPaiOrdem
fields = ('id', 'subject', 'subject_name', 'discipline', 'order')
You can use . in source argument for lookup related model's field like this:
subject_name = serializers.ReadOnlyField(source='subject.subject')

how to display tabularinline in api django rest framework?

I am with the demand of a system to manage the schedule of a cinema and to generate an api.
models.py
class Movie(models.Model):
title = models.CharField('título', max_length=250)
synopsis = models.TextField('sinopse', max_length=500)
year = models.IntegerField('ano')
# ... #
class Exhibition(models.Model):
movie = models.ForeignKey(Movie, verbose_name='Filme')
start = models.DateField('Início')
finish = models.DateField('Encerramento')
class Schedule(models.Model):
CINE_DERBY = 'CD'
CINE_CASAFORTE = 'CCF'
CINEMA = (
(CINE_CASAFORTE, 'Cinema Casa Forte'),
(CINE_DERBY, 'Cinema Derby')
)
data = models.DateTimeField('data')
local = models.CharField('local', max_length=5, choices=CINEMA)
exhibition = models.ForeignKey(Exhibition, verbose_name='Em cartaz')
admin.py
class ScheduleInline(admin.TabularInline):
model = Schedule
extra = 1
class MovieModelAdmin(admin.ModelAdmin):
list_display = ['title', 'synopsis', 'year']
class ExhibitionModelAdmin(admin.ModelAdmin):
inlines = [ScheduleInline]
list_display = ['movie', 'start', 'finish']
serializer.py
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model = Movie
fields = '__all__'
depth = 1
class ScheduleSerializer(serializers.ModelSerializer):
class Meta:
model = Schedule
fields = ['id', 'data', 'local', 'exhibition']
depth = 1
class ExhibitionSerializer(serializers.ModelSerializer):
movie = MovieSerializer(read_only=True)
movieId = serializers.PrimaryKeyRelatedField(write_only=True,
queryset=Movie.objects.all(),
source='movie')
schedule = ScheduleSerializer(many=True, read_only=True)
class Meta:
model = Exhibition
fields = ['movie', 'movieId', 'start', 'finish', 'schedule']
views.py
class MovieListViewSet(viewsets.ModelViewSet):
serializer_class = MovieSerializer
queryset = Movie.objects.all()
class ScheduleListViewSet(viewsets.ModelViewSet):
serializer_class = ScheduleSerializer
queryset = Schedule.objects.all()
class ExhibitionListViewSet(viewsets.ModelViewSet):
serializer_class = ExhibitionSerializer
queryset = Exhibition.objects.all()
I'm having trouble getting the movie times displayed on the display. I did based on the documentation of nested relationships, but the inline tabular part does not work: schedule is not displayed.
I would like api to generate the following:
[
{
"movie": {
"id": 1,
"title": "Vingadores: Guerra Infinita",
"synopsis": "Homem de Ferro, Thor, Hulk e os Vingadores se unem para combater seu inimigo mais poderoso, o maligno Thanos. Em uma missão para coletar todas as seis pedras infinitas, Thanos planeja usá-las para infligir sua vontade maléfica sobre a realidade.",
"year": 2018,
},
"schedule": [
{
"id": 1,
"data": "2018-04-26T14:00:00Z",
"local": "CFD",
},
{
"id": 2,
"data": "2018-05-03T20:00:00Z",
"local": "CFCF",
},
],
"start": "2018-04-30",
"finish": "2018-08-24"
}
]
The problem you are likely hitting is that DRF is looking for a field or a property on your Exhibition model called schedule but this doesn't exist.
I don't believe DRF can handle a reverse relation using just a field definition, you have to be more specific. Luckily DRF does make it easy to be more specific.
You can make use of the SerializerMethodField.
For example:
class ExhibitionSerializer(serializers.ModelSerializer):
movie = MovieSerializer(read_only=True)
movieId = serializers.PrimaryKeyRelatedField(write_only=True,
queryset=Movie.objects.all(),
source='movie')
schedule = serializers.SerializerMethodField()
class Meta:
model = Exhibition
fields = ['movie', 'movieId', 'start', 'finish', 'schedule']
def get_schedule(self, obj):
return [ScheduleSerializer(s).data for s in obj.schedule_set.all()]
It work for me. Thank you.
Take in addition for one_to_one relations. ))
#staticmethod
def get_picture(obj):
return PictureSerializer(obj.picture).data if hasattr(obj, 'picture') else 'no_picture_found'

django rest framework return a custom object using ModelSerializer and ModelViewSet

I have three models, three serializers, one modelviewset below.
I am using django-rest-framework to make a rest api for android.
The restaurant model was created first. Then I created a star model and an image model.
What I want to do is to add star and image objects into restaurant objects.
finally I've got what I want result but I think my viewset code looks like wrong..
Is there another way not to use "for loop"?
Models
class Restaurant(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
address = models.CharField(max_length=255)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
weather = models.ForeignKey(Weather, on_delete=models.CASCADE)
distance = models.ForeignKey(Distance, on_delete=models.CASCADE)
description = models.TextField('DESCRIPTION')
def __str__(self):
return self.name
class Star(models.Model):
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
rating = models.IntegerField('RATING')
def __str__(self):
return self.restaurant
class RestaurantImage(models.Model):
id = models.AutoField(primary_key=True)
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
path = models.CharField(max_length=255)
Serializer
class StarSerializer(serializers.ModelSerializer):
class Meta:
model = Star
fields = ('id', 'restaurant', 'user', 'rating', )
class RestaurantDetailSerializer(serializers.ModelSerializer):
category = CategorySerializer()
weather = WeatherSerializer()
distance = DistanceSerializer()
class Meta:
model = Restaurant
fields = ('id', 'name', 'address', 'category', 'weather',
'distance', 'description', )
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = RestaurantImage
fields = ('id', 'path', 'restaurant')
ViewSet
class RestaurantDetailInfoViewSet(viewsets.ModelViewSet):
queryset = Restaurant.objects.all()
serializer_class = RestaurantSerializer
def list(self, request, *args, **kwargs):
restaurant_list = Restaurant.objects.all()
restaurant_result = []
for restaurant in restaurant_list:
restaurantInfo = Restaurant.objects.filter(id=restaurant.pk)
restaurant_serializer = RestaurantDetailSerializer(restaurantInfo, many=True)
ratingAverageValue = Star.objects.filter(restaurant=restaurant.pk).aggregate(Avg('rating'))
images = RestaurantImage.objects.filter(restaurant=restaurant.pk)
image_serializer = ImageSerializer(images, many=True)
restaurant_dic = {
'restaurant': restaurant_serializer.data,
'ratingAverage': ratingAverageValue['rating__avg']
if ratingAverageValue['rating__avg'] is not None else 0,
'images': image_serializer.data
}
restaurant_result.append(restaurant_dic)
return Response(restaurant_result)
Result
[
{
"restaurant": [
{
"id": 1,
"name": "restaurant1",
"address": "address1",
"category": {
"c_id": 1,
"name": "foodtype1"
},
"weather": {
"w_id": 1,
"name": "sunny"
},
"distance": {
"d_id": 1,
"name": "inside"
},
"description": "description1"
}
],
"ratingAverage": 2.6667,
"images": [
{
"id": 1,
"path": "imagepath",
"restaurant": 1
}
]
},
Solution:
class RestaurantDetailSerializer(serializers.ModelSerializer):
category = CategorySerializer()
weather = WeatherSerializer()
distance = DistanceSerializer()
images = ImageSerializer(many=True, read_only=True)
ratingAverage = serializers.SerializerMethodField(read_only=True)
def get_ratingAverage(self, restaurant):
ratingAvgVal = Star.objects.filter(
restaurant=restaurant
).aggregate(Avg('rating'))['rating__avg']
return ratingAvgVal if ratingAvgVal is not None else 0
class Meta:
model = Restaurant
fields = ('id', 'name', 'address', 'category', 'weather',
'distance', 'description', 'images', 'ratingAverage', )
Explanation:
Here, I have nested the ImageSerializer in the RestaurantSerializer class, since you needed all the fields you've defined in ImageSerializer.
Then, for ratingAverage, I have used the SerializerMethodField which returns the value calculated (your logic) in the method I've defined for it, i.e. get_ratingAverage, which takes the Restaurant instance reference passed as an argument to the method for the field.