For my project I need to have a simple process
a form => many questions => for each questions a response type => if the response type is a multiple choice, then possible response are in a uniq group.
My goal is to be able to push though DRF/Django rest framework the whole initial form.
Here are my models:
class FormModels(models.Model):
class Status(models.IntegerChoices):
DRAFT = 1, _("DRAFT")
PUBLISHED = 2, _("PUBLISHED")
ARCHIVED = 5, _("ARCHIVED")
form_name = models.CharField(unique=True, blank=False, null=False, max_length=255)
form_model = models.CharField(unique=True, blank=False, null=False, max_length=255)
status = models.IntegerField(choices=Status.choices, blank=False, null=False, default=1)
def __str__(self):
return self.form_name
class FormResponseTypeModels(models.Model):
class Type(models.IntegerChoices):
TEXT = 1, _('TEXT')
MULTICHOICE = 2, _('MULTI')
type = models.IntegerField(choices=Type.choices, blank=False, null=False, default=1)
group = models.IntegerField(blank=False, null=True, default=1)
def __str__(self):
return str(self.type)
class Meta:
constraints = [
UniqueConstraint(fields=['group'], name='unique_group')
]
class MultipleChoiceDataModels(models.Model):
text = models.CharField(blank=False, null=False, max_length=255)
value = models.CharField(blank=False, null=False, max_length=255)
order = models.IntegerField(blank=False, null=False, default=1)
group_refid = models.ForeignKey(blank=False,
null=False,
default=1,
to=FormResponseTypeModels,
to_field="group",
related_name="groups",
on_delete=models.PROTECT)
def __str__(self):
return self.text
class FormQuestionModels(models.Model):
form_id = models.ForeignKey(to=FormModels, on_delete=models.PROTECT)
form_response_type = models.ForeignKey(to=FormResponseTypeModels, on_delete=models.PROTECT, related_name="test")
form_question = models.TextField(max_length=2000)
def __str__(self):
return self.form_question
Here is my serializers.py
class FormMultipleChoiceDataSerializer(serializers.ModelSerializer):
class Meta:
model = MultipleChoiceDataModels
fields = "__all__"
depth = 10
class FormResponseTypeSerializer(serializers.ModelSerializer):
groups = FormMultipleChoiceDataSerializer(many=True,
read_only=False,
required=False,
)
class Meta:
model = FormResponseTypeModels
fields = "__all__"
depth = 10
class FormQuestionSerializer(serializers.ModelSerializer):
form_response_type_set = FormResponseTypeSerializer(many=False,
read_only=False,
required=False
)
class Meta:
model = FormQuestionModels
fields = "__all__"
depth = 10
class FormSerializer(serializers.HyperlinkedModelSerializer):
questions = FormQuestionSerializer(many=True,
read_only=False,
source='formquestionmodels_set',
required=False)
class Meta:
model = FormModels
fields = "__all__"
def validate(self, attrs):
pass
return super().validate(attrs=attrs)
def create(self, validated_data):
# https://stackoverflow.com/questions/58023503/drf-serializer-field-renamed-to-its-source-in-validated-data
# question is 'formquestionmodels_set'
questions_data = validated_data.pop('formquestionmodels_set')
form = FormModels.objects.create(**validated_data)
for question_data in questions_data:
if "form_response_type_set" in questions_data:
form_response_type_set = question_data.pop("form_response_type_set")
max_group_id = None
if "formmultiplechoicedatamodel_set" in form_response_type_set:
form_response_type_set_groups = form_response_type_set.pop("formmultiplechoicedatamodel_set")
# find max group_id + 1
max_group_id = 1 + MultipleChoiceDataModels.objects.aggregate(Max("group_refid"))
for form_response_type_set_group in form_response_type_set_groups:
MultipleChoiceDataModels.objects.create(group_refid=max_group_id,
**form_response_type_set_group)
if max_group_id:
form_response_type = FormResponseTypeModels.objects.create(group=max_group_id,
**form_response_type_set)
else:
form_response_type = FormResponseTypeModels.objects.create(**form_response_type_set)
FormQuestionModels.objects.create(form_id=form, form_response_type=form_response_type, **question_data)
return form
Expected result would be:
{
"form_name": "test7",
"form_model": "test7",
"status": 1,
"questions": [
{
"form_question": "q1",
"form_response_type_set": {
"type": 1,
"group": [
{
"text": "a",
"value": "1",
"order": 1,
"group_refid": 1
}
]
}
},
{
"form_question": "q2",
"form_id": {
"form_name": "form_name",
"form_model": "form_model",
"status": 1
},
"form_response_type_set": {
"type": 1,
"group": [
{
"text": "a",
"value": "1",
"order": 1,
"group_refid": 1
}
]
}
}
]
}
But for the group part, I can't get it display. I got:
"questions": [
{
"id": 1,
"form_question": "q1",
"form_id": {
"id": 1,
"form_name": "t1",
"form_model": "t1",
"status": 2
},
"form_response_type": {
"id": 1,
"type": 1,
"group": null
}
},
{
"id": 2,
"form_question": "q2",
"form_id": {
"id": 1,
"form_name": "t1",
"form_model": "t1",
"status": 2
},
"form_response_type": {
"id": 2,
"type": 2,
"group": 1
}
}
],
"form_name": "t1",
"form_model": "t1",
"status": 2
}
]
With django shell I get this result:
FormResponseTypeSerializer():
id = IntegerField(label='ID', read_only=True)
groups = FormMultipleChoiceDataSerializer(many=True, read_only=False, required=False):
id = IntegerField(label='ID', read_only=True)
text = CharField(max_length=255)
value = CharField(max_length=255)
order = IntegerField(max_value=2147483647, min_value=-2147483648, required=False)
group_refid = NestedSerializer(read_only=True):
id = IntegerField(label='ID', read_only=True)
type = ChoiceField(choices=[(1, 'TEXT'), (2, 'MULTI')], required=False, validators=[<django.core.validators.MinValueValidator object>, <django.core.validators.MaxValueValidator object>])
group = IntegerField(allow_null=True, max_value=2147483647, min_value=-2147483648, required=False)
type = ChoiceField(choices=[(1, 'TEXT'), (2, 'MULTI')], required=False, validators=[<django.core.validators.MinValueValidator object>, <django.core.validators.MaxValueValidator object>])
group = IntegerField(allow_null=True, max_value=2147483647, min_value=-2147483648, required=False)
I've tried source and related name, many type of serializers, _set syntax for varialbe source ... , read 40+ stack overflow threads, but each time I'm stuck with this (also, if it matters, I would like to be able to post a new form at once with same endpoint)
Can you kindly point me to my error ?
I'm not sure what I did for it to work, but after lots of tries
using related_name in models,
changing the fields name to avoid using text, value and order,
deleting the database and apply migrations again,
set depth=1 to each parent serializer.
Now it works!
If someone have a good explanation, I would be glad to read it & learn!
Related
So I've built an API for movies dataset which contain following structure:
Models.py
class Directors(models.Model):
id = models.IntegerField(primary_key=True)
first_name = models.CharField(max_length=100, blank=True, null=True)
last_name = models.CharField(max_length=100, blank=True, null=True)
class Meta:
db_table = 'directors'
ordering = ['-id']
class Movies(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100, blank=True, null=True)
year = models.IntegerField(blank=True, null=True)
rank = models.FloatField(blank=True, null=True)
class Meta:
db_table = 'movies'
ordering = ['-id']
class Actors(models.Model):
id = models.IntegerField(primary_key=True)
first_name = models.CharField(max_length=100, blank=True, null=True)
last_name = models.CharField(max_length=100, blank=True, null=True)
gender = models.CharField(max_length=20, blank=True, null=True)
class Meta:
db_table = 'actors'
ordering = ['-id']
class DirectorsGenres(models.Model):
director = models.ForeignKey(Directors,on_delete=models.CASCADE,related_name='directors_genres')
genre = models.CharField(max_length=100, blank=True, null=True)
prob = models.FloatField(blank=True, null=True)
class Meta:
db_table = 'directors_genres'
ordering = ['-director']
class MoviesDirectors(models.Model):
director = models.ForeignKey(Directors,on_delete=models.CASCADE,related_name='movies_directors')
movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='movies_directors')
class Meta:
db_table = 'movies_directors'
ordering = ['-director']
class MoviesGenres(models.Model):
movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='movies_genres')
genre = models.CharField(max_length=100, blank=True, null=True)
class Meta:
db_table = 'movies_genres'
ordering = ['-movie']
class Roles(models.Model):
actor = models.ForeignKey(Actors,on_delete=models.CASCADE,related_name='roles')
movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='roles')
role = models.CharField(max_length=100, blank=True, null=True)
class Meta:
db_table = 'roles'
ordering = ['-actor']
urls.py
from django.urls import path, include
from . import views
from api.views import getMovies, getGenres, getActors
urlpatterns = [
path('', views.getRoutes),
path('movies/', getMovies.as_view(), name='movies'),
path('movies/genres/', getGenres.as_view(), name='genres'),
path('actor_stats/<pk>', getActors.as_view(), name='actor_stats'),
]
serializer.py
from rest_framework import serializers
from movies.models import *
class MoviesSerializer(serializers.ModelSerializer):
class Meta:
model = Movies
fields = '__all__'
class DirectorsSerializer(serializers.ModelSerializer):
class Meta:
model = Directors
fields = '__all__'
class ActorsSerializer(serializers.ModelSerializer):
class Meta:
model = Actors
fields = '__all__'
class DirectorsGenresSerializer(serializers.ModelSerializer):
class Meta:
model = DirectorsGenres
fields = '__all__'
class MoviesDirectorsSerializer(serializers.ModelSerializer):
movie = MoviesSerializer(many = False)
director = DirectorsSerializer(many = False)
class Meta:
model = MoviesDirectors
fields = '__all__'
class MoviesGenresSerializer(serializers.ModelSerializer):
movie = MoviesSerializer(many = False)
class Meta:
model = MoviesGenres
fields = '__all__'
class RolesSerializer(serializers.ModelSerializer):
movie = MoviesSerializer(many = False)
actor = ActorsSerializer(many = False)
class Meta:
model = Roles
fields = '__all__'
views.py
class getMovies(ListAPIView):
directors = Directors.objects.all()
queryset = MoviesDirectors.objects.filter(director__in=directors)
serializer_class = MoviesDirectorsSerializer
pagination_class = CustomPagination
filter_backends = [DjangoFilterBackend]
filterset_fields = ['director__first_name', 'director__last_name']
class getGenres(ListAPIView):
movies = Movies.objects.all()
queryset = MoviesGenres.objects.filter(movie__in=movies).order_by('-genre')
serializer_class = MoviesGenresSerializer
pagination_class = CustomPagination
filter_backends = [DjangoFilterBackend]
filterset_fields = ['genre']
class getActors(ListAPIView):
queryset = Roles.objects.all()
serializer_class = RolesSerializer
pagination_class = CustomPagination
def get_queryset(self):
return super().get_queryset().filter(
actor_id=self.kwargs['pk']
)
Now I want to count number of movies by genre that actor with specific pk played in getActors class.
Like the number of movies by genre that actor participated in. E.g. Drama: 2, Horror: 3
Right now I am getting the overall count of movies count: 2:
GET /api/actor_stats/17
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": 800480,
"movie": {
"id": 105231,
"name": "Everybody's Business",
"year": 1993,
"rank": null
},
"actor": {
"id": 17,
"first_name": "Luis Roberto",
"last_name": "Formiga",
"gender": "M"
},
"role": "Grandfather"
},
{
"id": 800481,
"movie": {
"id": 242453,
"name": "OP Pro 88 - Barra Rio",
"year": 1988,
"rank": null
},
"actor": {
"id": 17,
"first_name": "Luis Roberto",
"last_name": "Formiga",
"gender": "M"
},
"role": "Himself"
}
]
}
What is the optimized way of achieving the following:
number_of_movies_by_genre
Drama: 2
Horror: 3
UPDATE
class RolesSerializer(serializers.Serializer):
id = serializers.SerializerMethodField()
name = serializers.SerializerMethodField()
top_genre = serializers.SerializerMethodField()
number_of_movies = serializers.SerializerMethodField()
number_of_movies_by_genre = serializers.SerializerMethodField()
most_frequent_partner = serializers.SerializerMethodField()
class Meta:
model = Roles
fields = '__all__'
def get_id(self, obj):
return obj.actor.id
def get_name(self, obj):
return f'{obj.actor.first_name} {obj.actor.last_name}'
def get_top_genre(self, obj):
number_by_genre = Roles.objects.filter(actor = obj.actor.id
).values('movie__movies_genres__genre').annotate(
genre = F('movie__movies_genres__genre'),
number_of_movies=Count('movie__movies_genres__genre'),
)
data = [s['number_of_movies'] for s in number_by_genre]
highest = max(data)
result = [s for s in data if s == highest]
return result
def get_number_of_movies(self, obj):
number_of_movies = Roles.objects.filter(actor = obj.actor.id
).values('movie__name').count()
return number_of_movies
def get_number_of_movies_by_genre(self, obj):
number_of_movies_by_genre = Roles.objects.filter(actor = obj.actor.id
).values('movie__movies_genres__genre').annotate(
genre=F('movie__movies_genres__genre'),
number_of_movies=Count('movie__movies_genres__genre'),
).values('genre', 'number_of_movies')
return number_of_movies_by_genre
def get_most_frequent_partner(self, obj):
partners = Roles.objects.filter(actor = obj.actor.id
).values('movie__id')
result = Roles.objects.filter(movie__in = partners
).values('actor').exclude(actor=obj.actor.id).annotate(
partner_actor_id = F('actor'),
partner_actor_name = Concat(F('actor__first_name'), Value(' '), F('actor__last_name')),
number_of_shared_movies =Count('actor'),
).values('partner_actor_id', 'partner_actor_name', 'number_of_shared_movies')
return result
The problem with that code is: It repeats the results by the number of movies. For instance if the actor have 5 movies the results will be repeated 5 times. Another issue is: in order to get top_genre and most_frequent_partner I'm using max() but then I just get the numbers and not the actual name of genre in (top_genre) and actor name in (most_frequent_partner). Since I use max() in a way to get more than one value. For instance in the top_genre: If the actor have 3 Drama, 3 Comedy, 1 Horror, 1 Documentary, I get the max in that way: [3,3], but how can I get the actual names out of these results? Same goes to most_frequent_partner.
Results looks like this so far:
{
"next": null,
"previous": null,
"count": 4,
"pagenum": null,
"results": [
{
"id": 36,
"name": "Benjamin 2X",
"top_genre": [
2,
2
],
"number_of_movies": 4,
"number_of_movies_by_genre": [
{
"movie__movies_genres__genre": null,
"genre": null,
"number_of_movies": 0
},
{
"movie__movies_genres__genre": "Documentary",
"genre": "Documentary",
"number_of_movies": 2
},
{
"movie__movies_genres__genre": "Music",
"genre": "Music",
"number_of_movies": 2
}
],
"most_frequent_partner": []
},
{
"id": 36,
"name": "Benjamin 2X",
"top_genre": [
2,
2
],
"number_of_movies": 4,
"number_of_movies_by_genre": [
{
"movie__movies_genres__genre": null,
"genre": null,
"number_of_movies": 0
},
{
"movie__movies_genres__genre": "Documentary",
"genre": "Documentary",
"number_of_movies": 2
},
{
"movie__movies_genres__genre": "Music",
"genre": "Music",
"number_of_movies": 2
}
],
"most_frequent_partner": []
},
{
"id": 36,
"name": "Benjamin 2X",
"top_genre": [
2,
2
],
"number_of_movies": 4,
"number_of_movies_by_genre": [
{
"movie__movies_genres__genre": null,
"genre": null,
"number_of_movies": 0
},
{
"movie__movies_genres__genre": "Documentary",
"genre": "Documentary",
"number_of_movies": 2
},
{
"movie__movies_genres__genre": "Music",
"genre": "Music",
"number_of_movies": 2
}
],
"most_frequent_partner": []
},
{
"id": 36,
"name": "Benjamin 2X",
"top_genre": [
2,
2
],
"number_of_movies": 4,
"number_of_movies_by_genre": [
{
"movie__movies_genres__genre": null,
"genre": null,
"number_of_movies": 0
},
{
"movie__movies_genres__genre": "Documentary",
"genre": "Documentary",
"number_of_movies": 2
},
{
"movie__movies_genres__genre": "Music",
"genre": "Music",
"number_of_movies": 2
}
],
"most_frequent_partner": []
}
]
}
What I want to see in the end:
{
"next": null,
"previous": null,
"count": 2,
"results": [
{
"id": 18 (actor_id),
"name": Bruce Buffer (actor_name),
"number of movies": 2,
"top genre": Drama, Documentary,
"number of movies by genre": Drama: 1, Documentary: 1,
"most frequent partner": partner_actor_id, partner_actor_name, number_of_shared_movies,
}
]
}
If you want, the number of movies by genre for a given actor what you can do is annotate and count aggregate
return Roles.objects.filter(
actor_id=self.kwargs['pk']
).values('movie__movies_genres__genre').annotate(
no_of_movies=Count('movie__movies_genres__genre'),
genre=F('movie__movies_genres__genre'),
)
Here first we filtered roles for a given actor
then values will group by genre then annotation is computed over all members of the group that count and get genre
and you can use SerializerMethodField to these calculated results
if you have a huge dataset it will not perform well, but you can create indexes accordingly still it will cost you 2-3 queries
you can learn more about Django queryset API
There many ways to implement this route, it depends on many criteria and how much it will be used .
i think a correct way is to create a dedicated model that would store actor stats with a one to one relation to actor and recompute the value each time a movie is added. But If you add movie often it could slow down your database.
You can also accept to have some outdated data for a while and update the table regularly using a background job and maybe using custom sql query that will ensure you better performance (bulk update).
I would start from your model, you have genres defined as a CharField in two of your models. By not isolating them anywhere, you need to look in both tables for all types of genres. If do not, then you are just supposing that all the genres you have in one table is also on the other one, which could not be true.
Also, querying string fields is not very efficient when in comparison to a int PK, so from the point of view of scaling this is bad. (Of course, i am saying that in general, as a good practice and not focused specifically in movie genres)
Your best option would be to have either a Genre Model or a choice field, where you define all possible genres.
As for the counting, you would do that inside your serializer class, by using a serializermethodfield.
The way I am doing it is like in getProductList function in my views.py and it is giving me each product with its variants in different objects for eg the same product with different size is put into a different object even if the product is the same like so:
JSON:
[
{
"prod_id": {
"id": 3,
"prod_name": "CRUISER-149S-DEERCALF",
"category": 2
},
"size_id": {
"id": 2,
"name": "26"
},
"color_id": 2,
"image_id": {
"id": 10,
"prod_image": "/media/products/IMG_7617_ftgqoa.jpg"
}
},
{
"prod_id": {
"id": 3,
"prod_name": "CRUISER-149S-DEERCALF",
"category": 2
},
"size_id": {
"id": 3,
"name": "27"
},
"color_id": 2,
"image_id": {
"id": 10,
"prod_image": "/media/products/IMG_7617_ftgqoa.jpg"
}
}
]
Is there a way to maybe make it more optimized? like have only one product object that has all the info of a single product like size for example can be a property with values of all sizes in it like size: [26, 27] instead of a different object if a size is different.
models.py
class Products(models.Model):
prod_name = models.CharField(max_length=200)
category = models.ForeignKey(Categories,null=True, on_delete=models.SET_NULL)
def __str__(self):
return '%s'%(self.prod_name)
class Variants(models.Model):
prod_id = models.ForeignKey(Products, on_delete=models.CASCADE)
size_id = models.ForeignKey(Size, null=True, on_delete=models.SET_NULL, related_name='variants')
color_id = models.ForeignKey(Color, null=True, on_delete=models.SET_NULL, default='')
image_id = models.ForeignKey(Image,null=True, on_delete=models.SET_NULL, default='')
def __str__(self):
return '%s %s %s %s %s %s %s'%(self.id , self.prod_id, self.size_id, self.image_id, self.color_id, self.quantity, self.price)
serializer.py
class ProductsSerializer(serializers.ModelSerializer):
# variants = serializers.StringRelatedField(many=True)
class Meta:
model = Products
fields = "__all__"
class SizeSerializer(serializers.ModelSerializer):
class Meta:
model = Size
fields = "__all__"
class VariantsSerializer(serializers.ModelSerializer):
prod_id = ProductsSerializer(many=False, read_only=True)
image_id = ImageSerializer(many=False, read_only=True)
size_id = SizeSerializer(many=False, read_only=True)
class Meta:
model = Variants
fields = ['prod_id', 'size_id', 'quantity', 'price', 'color_id', 'image_id']
views.py
def getProductList(request):
print(request.GET.get('category'))
if(request.method == 'GET'):
if request.GET.get('category') == 'all' :
productList = Variants.objects.all().select_related()
serializer = VariantsSerializer(productList, many=True)
return JsonResponse(serializer.data, safe=False)
return JsonResponse({'details': 'Error in getting product list'})
I am using Django and Django-Rest-Framework to build an API for a battle system. In my code, I have 2 models: A parent model Battle and a child model Round. Round has some #property fields (start_time, end_time, score) which are calculated based on different values. When I access the Round route directly, I get the desired output:
http://127.0.0.1:8001/battle/rounds/1/
{
"id": 1,
"battle": "http://127.0.0.1:8001/battle/battles/1/",
"index": 0,
"contender_entry": null,
"opponent_entry": null,
"start_time": "2019-12-11T17:38:00Z",
"end_time": "2019-12-11T17:39:40Z",
"score": [
0,
0
]
}
however when I access the Battle route, the nested Rounds are returned, but only the database fields, not the properties:
http://127.0.0.1:8001/battle/battles/1/
{
"url": "http://127.0.0.1:8001/battle/battles/1/",
"id": 1,
"status": "live",
"start_time": "2019-12-11T17:38:00Z",
"round_length": "00:01:40",
...
"rounds": [
{
"url": "http://127.0.0.1:8001/battle/rounds/1/",
"beat": null,
"index": 0,
"battle": "http://127.0.0.1:8001/battle/battles/1/",
"contender_entry": null,
"opponent_entry": null
},
{
"url": "http://127.0.0.1:8001/battle/rounds/2/",
"beat": null,
"index": 1,
"battle": "http://127.0.0.1:8001/battle/battles/1/",
"contender_entry": null,
"opponent_entry": null
},
{
"url": "http://127.0.0.1:8001/battle/rounds/3/",
"beat": null,
"index": 2,
"battle": "http://127.0.0.1:8001/battle/battles/1/",
"contender_entry": null,
"opponent_entry": null
}
],
"current_round": null
}
I want the properties to be displayed in the nested Round objects in Battle. But I couldn't get it to work.
These are my models:
class Round(models.Model):
battle = models.ForeignKey(Battle, on_delete=models.CASCADE, related_name="rounds")
index = models.IntegerField()
contender_entry = models.OneToOneField(Entry, on_delete=models.DO_NOTHING, related_name="round_contender",
null=True)
opponent_entry = models.OneToOneField(Entry, on_delete=models.DO_NOTHING, related_name="round_opponent", null=True)
#property
def start_time(self):
return self.battle.start_time + (self.index * self.battle.round_length)
#property
def end_time(self):
return self.start_time + self.battle.round_length
#property
def score(self):
opponent_votes = self.votes.filter(favors="opponent").count()
contender_votes = self.votes.filter(favors="contender").count()
draw_votes = self.votes.filter(favors="draw").count()
return (opponent_votes + draw_votes, contender_votes + draw_votes)
class Battle(models.Model):
status = models.CharField(max_length=32, choices=BATTLE_STATUS_CHOICES, default="awaiting_approval")
contender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="contender_battles")
opponent = models.ForeignKey(User, on_delete=models.CASCADE, related_name="opponent_battles")
start_time = models.DateTimeField(default=timezone.now)
round_length = models.DurationField(default=timedelta(days=3))
And the serializers:
class RoundSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(source="pk", read_only=True)
class Meta:
model = Round
fields = ["id", "battle", "index", "contender_entry", "opponent_entry", "start_time", "end_time", "score"]
read_only_fields = ["id", "battle", "index", "start_time", "end_time", "score"]
class BattleSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(source='pk', read_only=True)
current_round = RoundSerializer(read_only=True)
class Meta:
model = Battle
fields = ["url", "id", "status", "start_time", "round_length",
"opponent", "contender", "rounds", "current_round"]
read_only_fields = ["contender", "rounds", "status"]
class BattleReadSerializer(BattleSerializer):
contender = UserSerializer(read_only=True)
opponent = UserSerializer(read_only=True)
class Meta:
model = Battle
fields = ["url", "id", "status", "start_time", "round_length",
"opponent", "contender", "rounds", "current_round"]
read_only_fields = ["contender", "rounds"]
depth = 1
Note that I have 2 Battle serializers: BattleSerializer used on POST and PUT and users hyperlinks instead of nested fields. BattleReadSerializer is used for GET and nests the output. BattleReadSerializer is the one used in the example above.
I already tried adding the fields to the RoundSerializer explicitly, like so:
class RoundSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(source="pk", read_only=True)
start_time = serializers.DateTimeField(read_only=True)
score = serializers.ListField(read_only=True)
But that didn't change anything. Is there any way to get the property fields to show (other than making them db fields and re-calculating them every so often)?
Try to add RoundSerializer serializer explicitly to the BattleReadSerializer serializer as below,
class BattleReadSerializer(BattleSerializer):
contender = UserSerializer(read_only=True)
opponent = UserSerializer(read_only=True)
rounds = RoundSerializer(read_only=True, many=True)
class Meta:
model = Battle
fields = ["url", "id", "status", "start_time", "round_length",
"opponent", "contender", "rounds", "current_round"]
read_only_fields = ["contender", "rounds"]
depth = 1 # remove this
I'm adding 'added' field to check which categories User's Post(Outfit) is added to. It sounds horrible, so let's dive in to the code.
I want to optimize get_categories(self, obj) function.
class CategorySerializer(serializers.ModelSerializer):
added = serializers.BooleanField()
class Meta:
model = Category
fields = (
'id',
'name',
'added'
)
class OutfitDetailSerializer(serializers.ModelSerializer):
def get_categories(self, obj):
user = self.context['request'].user
categories = Category.objects.filter(owner=user)
added = categories.extra(select={'added': '1'}).filter(outfits__pk=obj.pk)
added = list(added.values('added', 'name', 'id'))
added_f = categories.extra(select={'added': '0'}).exclude(outfits__pk=obj.pk)
added_f = list(added_f.values('added', 'name', 'id'))
categories = added + added_f
return CategorySerializer(categories, many=True).data
The output is below!
"categories": [{
"id": 1,
"name": "Gym",
"added": true
}, {
"id": 2,
"name": "School",
"added": false
}, {
"id": 3,
"name": "hollymo",
"added": true
}, {
"id": 4,
"name": "Normal",
"added": false
}, {
"id": 6,
"name": "New Category",
"added": false
}
]
Here is models.py
class Outfit(models.Model):
...
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
content = models.CharField(max_length=30)
...
class Category(models.Model):
name = models.CharField(max_length=20)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
outfits = models.ManyToManyField(Outfit, related_name="categories", blank=True)
main_img = models.ImageField(
upload_to=upload_location_category,
null=True,
blank=True)
...
here the repo for test
If i get you right, you can get necessary data with django raw sql:
q = """\
SELECT yourappname_category.id,
yourappname_category.name,
COUNT(outfit_id) > 0 as added
FROM yourappname_category
LEFT JOIN yourappname_category_outfits
ON yourappname_category.id = yourappname_category_outfits.category_id
AND yourappname_category_outfits.outfit_id=%s
WHERE yourappname_category.owner_id=%s
GROUP BY yourappname_category.id, yourappname_category.name"""
categories = Category.objects.raw(q, [obj.id, user.id])
results = [{'id': c.id, 'name': c.name, 'added': c.added} for c in categories]
If I understand your use case correctly you just want "to check which categories User's Post(Outfit) is added to". For that you would only need to return the ones with added = true right? and then you could leave the added key out.
as in:
"categories": [{
"id": 1,
"name": "Gym"
}, {
"id": 3,
"name": "hollymo"
}
]
If so, you could just use:
import Category from category.models
class CategoriesSerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name')
class OutfitDetailSerializer(serializers.ModelSerializer):
categories = CategoriesSerializer(many=True)
If instead your use case is to show a list of all categories and then do something with just the ones that the current outfit is added to, I'd suggest doing 2 API calls instead of your current logic; One with the answer I supplied above and one to get all categories. Then do that 'added' logic in your front-end as its presentation layer logic imo.
I'd certainly try to avoid doing raw SQL queries in Django, it cuts the purpose of migrations and is rarely necessary.
Given the following models:
class ErrorPhrase(models.Model):
...
document = models.ForeignKey(to=Document, on_delete=models.CASCADE)
text = models.CharField(max_length=256)
start_index = models.PositiveIntegerField()
correct_form = models.CharField(max_length=256, blank=True)
class ErrorTag(models.Model):
...
error_phrase = models.ForeignKey(to=ErrorPhrase, on_delete=models.CASCADE)
error = models.CharField(max_length=1, choices=error_choices)
category = models.CharField(max_length=1, choices=category_choices)
type = models.CharField(max_length=2, choices=type_choices)
I want to retrieve all the ErrorPhrase entries with their associated ErrorTags. I have used the values function like below:
error_phrases = ErrorPhrase.objects.values(
"id", "text", "start_index", "errortag__error",
"errortag__category", "errortag__type")
But this way I get one row of data for each of different ErrorTags of a particular ErrorPhrase object. For example:
[{
"errortag__error": "S",
"errortag__type": "WO",
"errortag__category": "S",
"text": "test",
"id": 40,
"start_index": 463
},
{
"errortag__error": "T",
"errortag__type": "OO",
"errortag__category": "P",
"text": "test",
"id": 40,
"start_index": 463
}...]
I'm looking for a way to group the data by ErrorPhrase fields ("id", "text", "start_index") and get all the ErrorTags of a particular ErrorPhrase object in a group. Something like this:
[{
"text": "test",
"id": 40,
"start_index": 463,
"error_tags": [{
"errortag__error": "S",
"errortag__type": "WO",
"errortag__category": "S"},
{
"errortag__error": "T",
"errortag__type": "OO",
"errortag__category": "P"}]
},...]
Can I do it in one query using Django QuerySet API ?
a bit change in your ErrorTag models:
class ErrorTag(models.Model):
...
error_phrase = models.ForeignKey(to=ErrorPhrase, on_delete=models.CASCADE,related_name='errortags')
error = models.CharField(max_length=1, choices=error_choices)
category = models.CharField(max_length=1, choices=category_choices)
type = models.CharField(max_length=2, choices=type_choices)
serializers.py
from rest_framework.serializers import SerializerMethodField
class ErrorPhraseListSerializer(ModelSerializer):
error_tags = SerializerMethodField('get_errors') #cannot use get_error_tags here
def get_errors(self,instance):
alist = []
tags_qs = instance.errortags.all()
for tag in tags_qs:
alist.append({
'errortag__error': tag.error,
'errortag__category':tag.category,
'errortag__type': tag.type
})
return alist
class Meta:
model = ErrorPhrase
fields = [
'document',
'text',
'start_index',
'correct_form ',
'error_tags',
]
Now in your views.py
class ErrorPhraseListAPIView(ListAPIView):
serializer_class = ErrorPhraseListSerializer
def get_queryset(self):
user = self.request.user
return File.objects.filter(user=user)