Django REST framework many to many serializer - serialization

I got models:
class Car:
name = models.CharField(max_length=50, blank=True, default='')
class Wheel:
name = models.CharField(max_length=50, blank=True, default='')
cars = models.ManyToManyField(Car)
and serializers:
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = ('name')
class WheelSerializer(serializers.ModelSerializer):
cars = CarSerializer(many=True, required=False)
class Meta:
model = Wheel
fields = ('name', 'cars')
It's works fine with Wheel case, it's shows me wheels and cars inside them. But I want to call cars and see wheels inside Cars. It's possible? Thanks!

Solution is to create new serializers:
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = ('name')
class WheelSerializer(serializers.ModelSerializer):
class Meta:
model = Wheel
fields = ('name', 'cars')
class CarWheelSerializer(serializers.ModelSerializer):
cars = CarSerializer(many=True, required=False)
class Meta:
....
and WheelCarSerializer same way.

Related

Cannot resolve keyword into field error while using drf model serializer and search_fields within field set?

SerializerClass:
class VacancySerializer(serializers.ModelSerializer):
organization_small_name = serializers.CharField(source='organization.short_name', read_only=True)
class Meta:
model = Vacancy
fields = ['organization', 'description', 'specs', 'type', 'publication_date',
'is_published', 'withdrawal_data', 'organization_small_name', ]
read_only_fields = ['publication_date', 'is_published', 'withdrawal_data',]
ViewSet:
class VacancyViewSet(viewsets.ModelViewSet):
queryset = Vacancy.objects.all()
serializer_class = VacancySerializer
filter_backends = [filters.SearchFilter]
search_fields = ['organization_small_name']
...
Model:
class Vacancy(models.Model):
organization = models.OneToOneField(DictOrganization, on_delete=models.CASCADE, related_name='vacancies')
description = models.TextField('Описание')
specs = models.ManyToManyField(DictSpec, blank=True)
type = models.CharField('Тип', max_length=20, choices=VacancyType.choices(), default=VacancyType.PRACTICE.value)
publication_date = models.DateField('Дата публикации', null=True, blank=True)
is_published = models.BooleanField('Опубликовано', default=False)
withdrawal_data = models.DateField('Дата снятия с публикации', null=True, blank=True)
My goal is to make API search by 'organization_small_name' field
that is in VacancySerializer.
Server runs successfully, but as soon as i add ?search parameter, i get next error:
Why it doesn't recognize 'organization_small_name' field, even thought it is decribed in serializer, and how can i fix it?

Django Model Design (Big model vs multiple)

I have a question about designing my models. Suppose I have a following model:
class Comment(models.Model):
who = models.ForeignKey(User, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
text = models.CharField(max_length=1000)
likes = models.IntegerField(default=0)
parent_comment = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name='child_comments')
Now I would like models for multiple topics (ShoppingList, Games,...). I came to two possible solutions and need help with deciding more suitable one.
1) Make Comment abstract and extend it for every new model wanted.
class ShoppingListComment(Comment):
shopping_list = models.ForeignKey(ShoppingList, related_name='shopping_comments', on_delete=models.CASCADE)
I could then query this game comments with something like:
ShoppingListComment.objects.all()
2) Add extra nullable Foreing keys directly to comment:
class BigCommentModel(models.Model):
who = models.ForeignKey(User, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
text = models.CharField(max_length=1000)
likes = models.IntegerField(default=0)
parent_comment = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name='child_comments')
shopping_list = models.ForeignKey(ShoppingList, related_name='shopping_comments', on_delete=models.CASCADE, null=True),
game = models.ForeignKey(Game, related_name='game_comments', on_delete=models.CASCADE, null=True)
I could then query this game comments with something lile:
BigCommentModel.objects.filter(game__isnull=False)

Django rest framework reverse relation serializers exclude fields

I have two models Question and Options
class Question(models.Model):
question_identifier = models.CharField(max_length=255)
question_text = models.TextField(blank=False)
question_category = models.ManyToManyField('Category')
question_tags = models.CharField(max_length=255, blank=True)
class Options(models.Model):
question = models.OneToOneField('Question', related_name='options', blank=False, null=False)
option1 = models.CharField(max_length=255,blank=False,null=True)
option2 = models.CharField(max_length=255,blank=False,null=True)
option3 = models.CharField(max_length=255,blank=True,null=True)
option4 = models.CharField(max_length=255,blank=True,null=True)
I have written a serializer for Question model which serializes options as well (reverse relation). I want to omit the question field from the Options? Is there a way to achieve this?
My Question Serializer:-
class QuestionSerializer(serializers.ModelSerializer):
"""
Serializer for Question object from qna.models
"""
question_category = CategorySerializer(many=True,write_only=True)
class Meta:
model = Question
fields = ('id', 'options', 'question_identifier','question_text','question_tags','question_category')
depth = 1
You can achieve that by creating a separate serializer for an Options model.And use it instead of default field, without depth value.
class OptionsSerializer(serializers.ModelSerializer):
class Meta:
model = Options
fields = ('option1', 'option2', 'option3')
class QuestionSerializer(serializers.ModelSerializer):
question_category = CategorySerializer(many=True,write_only=True)
options = OptionsSerializer()
class Meta:
model = Question
fields = ('id', 'options', 'question_identifier','question_text','question_tags','question_category')

Access child model class from parent model class object in Odoo8

Is there a way to access child model class object from parent model class object or now what child model class does this parent model class object has?
Here are my model classes:
class Content(models.Model):
_name = 'content'
title = fields.Char(string='Title', required=False)
summary = fields.Char(string='Summary', required=False)
description = fields.Char(string='Description', required=False)
class Video(models.Model):
_name = 'video'
_inherits = {'content': 'content_id'}
duration = fields.Float(string='Duration', required=False)
class Image(models.Model):
_name = 'image'
_inherits = {'content': 'content_id'}
width = fields.Float(string='Width', required=False)
height = fields.Float(string='Height', required=False)
If I have an object of "Content" class say "content1" that has a child object "image1", is there a way to access that "image1" object from "content1" object or now that type of "content1" is "Image"?
Content can have many child classes in future so I don't want to query all the child classes.
In Odoo you can travel bi-direction but your models should have configured like that,
class Content(models.Model):
_name = 'content'
_rec_name='title'
title = fields.Char(string='Title', required=False)
summary = fields.Char(string='Summary', required=False)
description = fields.Char(string='Description', required=False)
video_ids : fields.One2many('video','content_id','Video')
image_ids : fields.One2many('image','content_id','Video')
class Video(models.Model):
_name = 'video'
_inherit = 'content'
duration = fields.Float(string='Duration', required=False)
content_id = fields.Many2one('content','Content')
class Image(models.Model):
_name = 'image'
_inherit = 'content'
width = fields.Float(string='Width', required=False)
height = fields.Float(string='Height', required=False)
content_id = fields.Many2one('content','Content')
And you can access functionality of child classes by calling in this way.
for video in content1.video_ids:
## you can access properties of child classes like... video.duration
for image in content1.image_ids:
print image.width
Similarly you can call the method of child classes the same way.
If your aim is to do something else then specify it with example.

Issue with complex Django join query

I can't find a valid way with Django OMR in order to get : ( a raw query is also fine )
the Sites.sitename which made the Analysis where (Analysi_Items.name='somename' and Analysis_Items.value='somevalue') and (Analysi_items_name='somename' and Analysis_Items.value='somevalue') and (Analysis_items.name='somename' and Analysis_Items.value='somevalue').
class Sites(models.Model):
region = models.CharField(max_length=1000)
province = models.CharField(max_length=1000)
sitename = models.CharField(max_length=1000, primary_key=True)
class Meta:
verbose_name_plural = "Sites"
def __unicode__(self):
return self.sitename
class Analysis_Items(models.Model):
code = models.ForeignKey('Analysis')
name = models.CharField(max_lenght=100)
value = models.CharField(max_length=20)
class Meta:
verbose_name_plural = "Analysis Type"
class Analysis(models.Model):
date = models.DateField()
site = models.ForeignKey('Sites')
def __unicode__(self):
return str(self.date)
class Meta:
verbose_name_plural = "Analysis"
Hope this is clear enough. thank you in advance!
Site.objects.filter(analysis__analysis_items__name='some_name', analysis__analysis_items__value='some_value')
You can keep adding additional parameters in the same keep AND'ing them all together.