Filtering related_name field, in django - django

I am trying to filter related_name field with a query if it's possible. I serialize the tables.
class ProjectsSerializers(serializers.ModelSerializer):
class Meta:
model = Projects
fields = ["id", "project_id", "project_name", "tasks"]
depth = 1
Above in the fields list. tasks is the related_table so in the tasks table I have task_created_at field and when I retrieve the projects table. I want to filter it by that field.
def get_projects(request):
projects = Projects.objects.filter(task_created_at__startswith="2020-04")
serializer = ProjectsSerializers(projects, many=True)
return Response(serializer.data)
Of course this: task_created_at__startswith="2020-04" isn't working. Because task_created_at is not in the projects. it's in the related_name which is tasks. So is there a way to filter tasks with getting projects
and the relevent models:
class Projects(models.Model):
project_id = models.CharField(max_length=255)
project_name = models.CharField(max_length=255)
def __str__(self):
return self.project_name
class Meta:
db_table = "projects"
class Tasks(models.Model):
projects = models.ForeignKey(Projects, on_delete=models.CASCADE, related_name='tasks', blank=True, null=True)
task_price = models.IntegerField(blank=True, null=True)
task_total_price = models.IntegerField(blank=True, null=True)
task_created_at = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return self.ad_kind
class Meta:
db_table = "tasks"
the example data:
[
{
"id": 6,
"order_id": null,
"project_id": "23123",
"project_name": "プレサンス グラン 茨木駅前",
"company_name": null,
"analytics_id": null,
"advertisements": [],
"tasks": [
{
"id": 1,
"task_total_price": null,
"task_created_at": "2020-04-02",
"task_due_date": "2020-04-07",
"task_modified_at": "2020-04-07T06:42:41.447Z",
"projects": 6
},
{
"id": 2,
"task_total_price": null,
"task_created_at": "2020-02-02",
"task_due_date": "2020-03-07",
"task_modified_at": "2020-04-07T06:42:41.447Z",
"projects": 6
},
]
}
]

You can JOIN two tables/models by __ (a double underscore).
from django.db.models import Prefetch
def get_projects(request):
projects = Projects.objects.prefetch_related(
Prefetch('tasks', queryset=Tasks.objects.filter(task_created_at__istartswith='2020-04'))
).filter(tasks__task_created_at__istartswith='2020-04')
serializer = ProjectsSerializers(projects, many=True)
return Response(serializer.data))
Reference
Lookups that span relationships
Prefetch(...)

You will need to use a subquery:
def get_projects(request):
project_ids = Task.objects.filter(
task_created_at__startswith='2020-04').values('project_id')
projects = Project.objects.filter(id__in=project_ids)
serializer = ProjectsSerializers(projects, many=True)
return Response(serializer.data)
Also, please don't use plural table names ;-)
Lastly, I'd recommend using a DateTimeField for storing dates, instead of using a CharField.

To be able to dynamically change the representation of an object, you can modify the serializer. One way to filter the tasks is to provide a serializers.SerializerMethodField that filters the tasks dynamically.
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = [ ... your fields ... ]
class ProjectSerializer(serializers.ModelSerializer):
filtered_tasks = serializers.SerializerMethodField()
class Meta:
model = Project
fields = ["id", "project_id", "project_name", "filtered_tasks"]
depth = 1
def get_filtered_tasks(self, obj):
tasks = Task.objects.filter(created_at__startswith="2020-04")
return TaskSerializer(tasks, many=True).data
However, I don't like this approach. I think you should reconsider how you present the data. It feels like your binding the data too hard together. Although, I don't know your use-case so I cannot come with any concrete suggestions.
Also, I've changed the names here so the models are singular, as it's the convention.

Related

DRF how to get items grouping by categories

I understand that my question is repeated often, but I'm stuck with this.
I want to make a simple API with DRF. I have two models:
models.py
class Rubrics(models.Model):
id = models.AutoField(primary_key=True)
rubric = models.CharField(max_length=255, blank=True, null=True)
class Books(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=255, blank=True, null=True)
author = models.CharField(max_length=255, blank=True, null=True)
date = models.CharField(max_length=255, blank=True, null=True)
rubrics = models.ForeignKey('Rubrics', on_delete=models.DO_NOTHING, related_name='books', blank=True, null=True)
I'd like to view serialized results like this:
[
rubric1: [
{
title: "title1",
author:"author1"
},
book_obj2,
so on
],
rubric2: [
book_obj4,
book_obj5
]
]
views.py
class BooksByRubricView(APIView):
"""List of books by rubrics"""
def get(self, request):
last_date = Books.objects.latest("date").date
books_last = Books.objects.filter(date=last_date)
serializer = RubricsSerializer(books_last, many=True)
return Response(serializer.data)
I try a lot of examples in this theme:
#sorry this garbage
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Books
#fields = ("title",)
exclude = ()
class RubricsSerializer(serializers.ModelSerializer):
rubrics = BookSerializer(read_only=True)
class Meta:
model = Rubrics
fields = ("rubrics",)
#exclude = ()
"""
class RubricSerializer(serializers.ModelSerializer):
#rubrics = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
#books = RecursiveSerializer(many=True)
#print(books)
rubrics = RubricSerializer(read_only=True)
#books = BooksListSerializer(many=True)
class Meta:
model = Books
fields = ("title", "rubrics",)
#fields = ['rubric', 'rubrics']
#fields = ['books', 'rubrics']
"""
But maybe I don't understand the principles of reverse relationships and serializing in DRF. Please, tell me WAIDW. Thanks.
UPD.
I want to operate only on specified sets of data (for example, work with the last uploaded books), not on the whole table Books. So I want to view only rubrics, that are in this set, not all rubrics from table Rubrics. Yes, books have only one rubric id in a specified field, and the rubric has a one-to-many relationship to books.
Well, that's JSON I want to see (of course, all characters appearing in this work, are fictitious. Any resemblance to actual persons, living or dead, is purely coincidental.):
{
"rubric1": [{
"author": "Marley W. Watkins",
"title": "A Step-By-Step Guide to Exploratory Factor Analysis with Stata"
}, {
"author": "Robert E. Davis",
"title": "Auditing Information and Cyber Security Governance; A Controls-Based Approach"
}, {
"author": "Gerhard X. Ritter, Gonzalo Urcid",
"title": "Introduction to Lattice Algebra: With Applications in AI, Pattern Recognition, Image Analysis, and Biomimetic Neural Networks"
}],
"rubric2": [{
"author": "Richard Cross and JT Paasch",
"title": "The Routledge Companion to Medieval Philosophy"
}, {
"author": "Nicholas Allott (editor), Terje Lohndal (editor), Georges Rey (editor)",
"title": "A Companion to Chomsky"
}, {
"author": "Olakunle George",
"title": "A Companion to African Literatures"
}, {
"author": "Tim Byrnes, Ebubechukwu O. Ilo-Okeke",
"title": "Quantum Atom Optics: Theory and Applications to Quantum Technology"
}],
"rubric3": [{
"author": "Hiroyoshi Naito",
"title": "Organic Semiconductors for Optoelectronics"
}, {
"author": "Bassem R. Mahafza, Scott C. Winton",
"title": "Handbook of Radar Signal Analysis"
}, {
"author": "Sean McManus, Mike Cook",
"title": "Raspberry Pi For Dummies, 4th Edition"
}]
}
I realize it in plain Django:
class BooksByRubricView(APIView):
"""List of books by rubrics"""
def get(self, request):
last_date = Books.objects.using('books').latest("date").date
books_last = Books.objects.using('books').filter(date=last_date)
categories = []
res_dict = {}
for item in books_last:
categories.append(item.rubrics_id)
categories = set(categories)
for item in categories:
temp_list = []
temp_qs = books_last.filter(rubrics_id=item)
for i in temp_qs:
temp_list.append({"author": i["author"], "title": i["title"]})
res_dict["rubric"+str(item)]=list(temp_list)
# res = json.dumps(res_dict)
return JsonResponse(res_dict, safe=False, json_dumps_params={'ensure_ascii': False})
can I realize it with DRF serializers or simplest way is not f*cking any brains and return JSON as above?
Update2:
Well, after some magic with serializers and generic.APIView I've got a result not exactly expected, but very closest to that. Example (of course, all characters appearing in this work, are fictitious. Any resemblance to real persons, living or dead, is purely coincidental)
views.py
class BooksByRubricView2(generics.ListAPIView):
"""Books grouped by rubrics"""
serializer_class = RubricsSerializer2
queryset = Rubrics.objects.all()
#OR without generic
class BooksByRubricView3(APIView):
def get(self, request):
r = Rubrics.objects.all()
serializer=RubricsSerializer2(r,many=True)
return Response(serializer.data)
serializers.py
class FilteredListSerializer(serializers.ListSerializer):
"""Serializer to filter Book table, look for latest date for every rubric"""
def to_representation(self, data):
latest_data = data.latest("date").date
data = data.filter(date=latest_data)
return super(FilteredListSerializer, self).to_representation(data)
class BookSerializer2(serializers.ModelSerializer):
class Meta:
model = Books
list_serializer_class = FilteredListSerializer
fields = (
"title",
"author",
"date")
class RubricsSerializer2(serializers.ModelSerializer):
books = BookSerializer2(many=True, read_only=True)
class Meta:
model = Rubrics
fields = ("rubric", "books",)
result:
[
{
"rubric": "Computers",
"books": [
{
"title": "A Step-By-Step Guide to Exploratory Factor Analysis with Stata",
"author": "Marley W. Watkins",
"date": "2021-08-08"
},
{
"title": "Auditing Information and Cyber Security Governance; A Controls-Based Approach",
"author": "Robert E. Davis",
"date": "2021-08-08"
}
]
},
{
"rubric": "Education",
"books": [
{
"title": "The Routledge Companion to Medieval Philosophy",
"author": "Richard Cross and JT Paasch",
"date": "2021-08-08"
}
]
},
so on
}
It's a dirty way because every Rubric from table Rubrics creates its own query to table Books and each Rubric has its latest date. But DRF filtering will be the next step.
There is no field rubrics in Rubrics model, available fields are:
id,rubric from model itself,
books_set which represent all books that have FK reference to that Rubrics instance. Take a look at this official docs
Book have one rubric (rubrics foreign key), and rubrics have multiple books (books_set). I would also suggest changing FK name from rubrics to rubric since there can be only one.
Try this and work from there:
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Books
#fields = ("title",)
exclude = ()
class RubricsSerializer(serializers.ModelSerializer):
class Meta:
model = Rubrics
fields = ("books_set",)
#exclude = ()
First i've tried to get the result that you wanted using your view and just dit not worked! So I've created another view:
from .serializers import *
from rest_framework import generics
from .models import *
class BooksByRubricView(generics.ListAPIView):
serializer_class = RubricsSerializer
queryset = Rubric.objects.all()
# You should try!
And course I also had to create a path (Just for tests! Ignore it!):
from django.urls import path
from .views import BooksByRubricView
urlpatterns = [
path('books/', BooksByRubricView.as_view(), name='books')
]
In your models:
from django.db import models
class Rubric(models.Model):
id = models.AutoField(primary_key=True) # Do not use plural in the models name!
rubric_name = models.CharField(max_length=255, blank=True, null=True)
class Meta:
ordering = ['id'] # Create a ordering!
def __str__(self):
return self.rubric_name
class Book(models.Model):
rubric = models.ForeignKey(Rubric, related_name='rubrics', on_delete=models.CASCADE)
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=255, blank=True, null=True)
author = models.CharField(max_length=255, blank=True, null=True)
date = models.CharField(max_length=255, blank=True, null=True)
class Meta:
ordering = ['id'] # Create a ordering!
In your serializers.py:
from rest_framework import serializers
from .models import *
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = (
"title",
"author",
"date"
)
class RubricsSerializer(serializers.ModelSerializer):
rubrics = BookSerializer(many=True, read_only=True)
class Meta:
model = Rubric
fields = (
"id", # Put an Id if you want!
"rubrics",
)
Maybe the only problem was with your view! So I just did all this to get the result that you want but localy; images of the result:

Allow related field in post request in DRF

I have created model with many to many relationship and I have join table when I keep additional variable for it:
class BorderStatus(models.Model):
STATUS_CHOICES = [("OP", "OPEN"), ("SEMI", "CAUTION"), ("CLOSED", "CLOSED")]
origin_country = models.ForeignKey(OriginCountry, on_delete=models.CASCADE, default="0")
destination = models.ForeignKey(Country, on_delete=models.CASCADE, default="0")
status = models.CharField(max_length=6, choices=STATUS_CHOICES, default="CLOSED")
extra = 1
class Meta:
unique_together = [("destination", "origin_country")]
verbose_name_plural = "Border Statuses"
def __str__(self):
return (
f"{self.origin_country.origin_country.name} -> {self.destination.name}"
f" ({self.status})"
)
Other models:
# Create your models here.
class Country(models.Model):
name = models.CharField(max_length=100, unique=True, verbose_name='Country')
class Meta:
verbose_name_plural = "Countries"
def __str__(self):
return self.name
class OriginCountry(models.Model):
origin_country = models.ForeignKey(
Country, related_name="origins", on_delete=models.CASCADE
)
destinations = models.ManyToManyField(
Country, related_name="destinations", through="BorderStatus"
)
class Meta:
verbose_name_plural = "Origin Countries"
def __str__(self):
return self.origin_country.name
Here is my serializer for the endpoint:
class BorderStatusEditorSerializer(serializers.ModelSerializer):
"""Create serializer for editing single connection based on origin and destination name- to change status"""
origin_country = serializers.StringRelatedField(read_only=True)
destination = serializers.StringRelatedField(read_only=True)
class Meta:
model = BorderStatus
fields = ('origin_country', 'destination', 'status')
And my endpoint:
class BorderStatusViewSet(viewsets.ModelViewSet):
queryset = BorderStatus.objects.all()
serializer_class = BorderStatusEditorSerializer
filter_backends = (DjangoFilterBackend,)
filter_fields=('origin_country','destination')
The problem Im having is that I cant create any new combination for the BorderStatus model in this serializer via post request.
If I remove the lines:
origin_country = serializers.StringRelatedField(read_only=True)
destination = serializers.StringRelatedField(read_only=True)
Then the form will work, but then I wont have the string representation of those variables, instead I get IDs.
Is there any way to allow request to accept origin_country and destination while being related fields?
EDIT:
To clarify how OriginCountry works, it is has a nested field:
[{ "id": 1
"origin_country": "Canada",
"dest_country": [
{
"id": 1,
"name": "France",
"status": "CLOSED"
},
{
"id": 2,
"name": "Canada",
"status": "OP"
}
]
},
]
You can try to override perform_create method of the viewset to make the necessary adjustments on-the-fly when new entry is posted:
class BorderStatusViewSet(viewsets.ModelViewSet):
queryset = BorderStatus.objects.all()
serializer_class = BorderStatusEditorSerializer
filter_backends = (DjangoFilterBackend,)
filter_fields=('origin_country','destination')
def perform_create(self, serializer):
origin_country, _ = models.Country.get_or_create(name=self.request.data.get('origin_country')
destination, _ = models.Country.get_or_create(name=self.request.data.get('destination')
return serializer.save(origin_country=origin_country, destination=destination)
Maybe you will also need to adjust your serializer to have:
class CountrySerializer(serializers.ModelSerializer):
class Meta:
model = Country
fields = ['name']
class BorderStatusEditorSerializer(serializers.ModelSerializer):
origin_country = CountrySerializer()
destination = CountrySerializer()
...
Yes, I will try to give this combination.
You get this error because of Incorrect Type exception. Django checks data type validation on the serializer. For example here your dest_country returns a list of dicts but in your model it is a primary key (pk)
That's why on post django says : pk value expected, list received
But you can solve this error by using two different serializers (one to post another by default)
1. Create two different serializers
class BorderStatusEditorSerializer(serializers.ModelSerializer):
"""The First serialiser by default"""
origin_country = serializers.StringRelatedField(read_only=True)
destination = serializers.StringRelatedField(read_only=True)
class Meta:
model = BorderStatus
fields = ('origin_country', 'destination', 'status')
class BorderStatusEditorCreateSerializer(serializers.ModelSerializer):
"""The Second serialiser for create"""
class Meta:
model = BorderStatus
fields = ('origin_country', 'destination', 'status')
2.Add get_serializer_class method to for Viewset
class BorderStatusViewSet(viewsets.ModelViewSet):
queryset = BorderStatus.objects.all()
filter_backends = (DjangoFilterBackend,)
filter_fields=('origin_country','destination')
serializer_classes = {
'create': BorderStatusEditorCreateSerializer, # serializer used on post
}
default_serializer_class = BorderStatusEditorSerializer # Your default serializer
def get_serializer_class(self):
return self.serializer_classes.get(self.action, self.default_serializer_class)

DRF How to change the field key names in JSON response

I want to display all objects of a particular model, and it's related objects ( object-wise ).
Is there a way to change/customize the JSON output? (In terms of the key names, values, or the nesting?)
views.py
#api_view(['GET'])
def api(request):
q = Question.objects.all()
s = QuestionSerializer(q, many=True)
print(ChoiceSerializer())
return Response(s.data)
serializers.py
class QuestionSerializer(serializers.ModelSerializer):
choices = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = Question
fields = '__all__'
models.py
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField(auto_now_add=True, editable=False, name='pub_date')
def __str__(self):
return self.question_text
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='choices')
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
def related_question(self):
q = self.question.question_text
return q
Output
HTTP 200 OK
Allow: OPTIONS, GET
Content-Type: application/json
Vary: Accept
[
{
"id": 1,
"choices": [
1,
2,
3
],
"question_text": "Question 1",
"pub_date": "2020-12-19T23:07:25.071171+05:30"
},
{
"id": 2,
"choices": [
4,
5
],
"question_text": "Question 2",
"pub_date": "2020-12-21T13:58:37.595672+05:30"
}
]
In the output, choices shows the pk of the objects.
How can I change that to show, say, the choice_text or a custom string?
Also, can the way the objects are nested be customized?
EDIT: When I asked if there is a way to exercise more control, I meant control over the depth of JSON response.
You can use serializer's method field to replace choices key with any related model fields that you want. For instance
class QuestionSerializer(serializers.ModelSerializer):
choices = serializers.SerializerMethodField('get_choices')
class Meta:
model = Question
fields = '__all__'
def get_choices(self, obj):
return obj.choices.values('choice_text').distinct() # or values('id', 'choice_text') based on your requirements
Note that values are a better way than iterating through all objects as a performance point of view (like [choice.choice_text for choice in question.choices.all()], etc).
EDIT: SerializerMethodField is used when we want to run some custom logic to populate a particular field.
When using ModelSerializer, the source keyword can be used to access fields (related, non related both) or even rename fields in the case where the person interacting with the endpoint requires a different name.
Example for renaming(using models mentioned in the question)
class QuestionSerializer(serializers.ModelSerializer):
poll_question = serializers.CharField(source='question_text')
class Meta:
model = Question
fields = '__all__'
Example for getting a FK related field:
class ChoiceSerializer(serializers.ModelSerializer):
poll_question = serializers.CharField(source='question.question_text')
class Meta:
model = Choice
fields = '__all__'
This is a very good foundational read for understanding how and when to use serializers in DRF.
You can use serializers.SerializerMethodField(...) if you want more control over what you wish to return
class QuestionSerializer(serializers.ModelSerializer):
choices = serializers.SerializerMethodField()
def get_choices(self, question):
return [choice.choice_text for choice in question.choices.all()]
class Meta:
model = Question
fields = '__all__'
Instead of PrimaryKeyRelatedField, consider using SlugRelatedField. For example:
class QuestionSerializer(serializers.ModelSerializer):
choices = SlugRelatedField(many=True, read_only=True, slug_field='choice_text')
class Meta:
model = Question
fields = '__all__'
Also, you need to make choice_text field unique, ie add unique=True for this to work.
choice_text = models.CharField(max_length=200, unique=True)
FYI, you can remove __unicode__ method from your model definations. Explanation can be found in this Django documentation link.

Remove results with field==0 from serializer response

I use ModelSerializer to return serialized data of a model:
class CategorySerializer(serializers.ModelSerializer):
category_count = serializers.SerializerMethodField('_category_count')
def _category_count(self, obj):
category_obj = Category.objects.get(id=obj.id)
questions_count = Question.objects.filter(category=category_obj).count()
return questions_count
class Meta:
model = Category
fields = ["id", "category", "category_count"]
What I get write now is here:
[{
"category": "orzecznictwo lekarskie",
"category_count": 0,
"id": 9
},
{
"category": "zdrowie publiczne",
"category_count": 1,
"id": 10
}
]
I want to remove objects with category_count == 0 from serialization
[
{
"category": "zdrowie publiczne",
"category_count": 1,
"id": 10
}
]
Thank you for your help.
EDIT:
class Question(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
question = models.TextField(blank=True, null=True)
(...)
class Category(models.Model):
category = models.TextField()
category_slug = models.CharField(max_length=50)
You're generating the field inside the serializer and then want to discard the object. That's not how things work: serializers merely change representation of data. Which data is displayed is determined in views.
class CategoryListView(generics.ListAPIView):
def get_queryset(self):
return models.Category.objects.annotate(
question_count=Count("question_set")
).exclude(question_count=0)
And in the serializer, you don't have to create the count any more and add the 'question_count' to Meta.fields.
Recommended reading.
Edit:
Forgot that DRF will check the field on the model and fail, so you need to declare the field:
class CategoryWithQuestionCount(serializers.ModelSerializer):
question_count = serializers.IntegerField(read_only=True)
class Meta:
model = models.Category
fields = ("pk", "category", "question_count")
I'm not sure about removing it in the ModelSerializer. But you can try overriding get_queryset() or changing the queryset in your View:
queryset = Class.objects.exclude(dzial_liczba_pytan=0)

Different write and read operations with DRF

I am using Django Rest Framework for a project and I am running into a problem. When the frontend creates a Team they want to reference all relationships with an ID, but when getting the Team, they want the data from the relationship. How can I achieve this?
models:
class Team(models.Model):
class Meta:
db_table = "team"
team_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
class Organization(models.Model):
class Meta:
db_table = "organization"
organization_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
class Position(models.Model):
class Meta:
db_table = "position"
position_id = models.AutoField(primary_key=True)
team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="positions")
class Player(model.Model):
class Meta:
db_table = "player"
player_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
positions = models.ManyToManyField(Position, related_name="players")
serializers:
class TeamSerializer(serializers.ModelSerializer):
class Meta:
model = Team
fields = ["team_id", "name", "organization", "positions"]
positions = PositionSerializer(many=True) # This is merely for output. There is no need to create a position when a team is created.
organization = OrganizationSerializer() # Since an organization already exists I'd like to just give an organization_id when creating/editing a team.
# I don't think the other serializers matter here but can add them on request.
So when doing POST or PATCH on a team, I'd like the front end to be able to pass this payload
{
"name": "My Team",
"organization": 1
}
but when doing a GET on a team, I'd like the front end to receive this response.
{
"team_id": 1,
"name": "My Team",
"organization": {
"organization_id": 1,
"name": "My Organization"
},
"positions": [{
"position_id": 1,
"players": [{
"player_id": 1,
"name": "Member 1"
}
]
}
Is there a a way to achieve this?
In such situations define two serializers, one is for read operations and one is for write operations.
class TeamWriteSerializer(serializers.ModelSerializer):
# see, here no nested relationships...
class Meta:
model = Team
fields = ["name", "organization"]
class TeamReadSerializer(serializers.ModelSerializer):
class Meta:
model = Team
fields = ["team_id", "name", "organization", "positions"]
positions = PositionSerializer(many=True)
organization = OrganizationSerializer()
and now, use these two serializers properly in your views. For example, I hope you are using the ModelViewSet in views,
class TeamModelViewSet(viewsets.ModelViewSet):
def get_serializer_class(self):
if self.request.method.lower() == 'get':
return TeamReadSerializer
else:
return TeamWriteSerializer