Django Rest Framework not saving all foreign key objects - python-3.x

I am going to create a conference and select multiple departments, it is working when I send post request but in GET resquest not getting objects.
class DepartmentModel(models.Model):
name = models.CharField(max_length=255)
conference = models.ForeignKey('ConferenceModel', on_delete=models.CASCADE, null=True,
related_name='conference_departments')
class ConferenceModel(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
description = models.CharField(max_length=255, null=True)
serializers.py
class DepartmentField(serializers.PrimaryKeyRelatedField):
def to_representation(self, value):
pk = super(DepartmentField, self).to_representation(value)
try:
item = DepartmentModel.objects.get(pk=pk)
serializer = DepartmentSerializer(item)
return serializer.data
except DepartmentModel.DoesNotExist:
return None
def get_choices(self, cutoff=None):
queryset = self.get_queryset()
if queryset is None:
return {}
return OrderedDict([(item.id, str(item)) for item in queryset])
class ConferenceModelSerializer(serializers.ModelSerializer):
conference_departments = DepartmentField(queryset=DepartmentModel.objects.all(), many=True)
meeting_participants = SelectItemField(model='account.User', extra_field=['first_name', 'last_name'], many=True)
class Meta:
model = ConferenceModel
fields = '__all__'
request
{
"conference_departments": [
3, 4, 5, 7, 8
],
"meeting_participants": [
10, 12, 15
],
"description": "Bla bla bla"
}
it returns the expected result but If I want to save another object and get all objects it does not return objects but the latest one does.
here you can see from the image below
id: 19 is the latest saved object it returns department objects but id: 18 does not!
can anybody help me please? any help would be appreciated! Thanks in advance!

class DepartmentSerializer(serializers.ModelSerializer):
...
class Meta:
model = DepartmentModel
fields = '__all__'
class ConferenceModelSerializer(serializers.ModelSerializer):
conference_departments = DepartmentSerializer(required=False, many=True)
meeting_participants = SelectItemField(model='account.User', extra_field=['first_name', 'last_name'], many=True)
class Meta:
model = ConferenceModel
fields = '__all__'
Nested relationships
Writable nested serializers

Related

Error: (admin.E035) The value of 'readonly_fields[0]' is not a callable

Summarize the problem
<class 'news.admin.NewsAdmin'>: (admin.E035) The value of 'readonly_fields[0]' is not a callable, an attribut
e of 'NewsAdmin', or an attribute of 'news.News'.
This all code error. I learn Django, and write code how in author. But write this error :(
Describe what you`ve tried
I immediately insert problem in search, but not found decision
I read this question, but it not finished
This question elementary, author question not correct write variable
Show some code
admin.py
from django.contrib import admin
from .models import News, Category
class NewsAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'category', 'create_at', 'updated_at', 'is_published')
list_display_links = ('id', 'title',) # what be links in model
search_fields = ('title', 'content',)
list_editable = ('is_published',) # redact is published in menu
list_filter = ('is_published', 'category',) # create table, what in be setting sorted
fields = ('title', 'category', 'content', 'photo', 'get_photo', 'is_published', 'views',
'create_at', 'updated_at')
readonly_fields = ('get_photo', 'views', 'create_at', 'updated_at')
class CategoryAdmin(admin.ModelAdmin):
list_display = ('id', 'title') # displays
list_display_links = ('id', 'title') # links
search_fields = ('title',)
admin.site.register(News, NewsAdmin)
admin.site.register(Category, CategoryAdmin)
models.py
from django.db import models
from django.urls import reverse
class News(models.Model):
title = models.CharField(max_length=150)
content = models.TextField(blank=True)
create_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
photo = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
is_published = models.BooleanField(default=True)
category = models.ForeignKey('Category', on_delete=models.PROTECT)
views = models.IntegerField(default=0)
def get_absolute_url(self):
return reverse('view_news', kwargs={"news_id": self.pk})
def __str__(self): # return number position model
return self.title
objects = models.Manager()
class Meta:
verbose_name = 'NEWS'
verbose_name_plural = 'NEWS'
ordering = ['-create_at']
class Category(models.Model):
title = models.CharField(max_length=150, db_index=True, verbose_name='Title category')
def get_absolute_url(self):
return reverse('category', kwargs={"category_id": self.pk})
class Meta:
verbose_name = 'Category'
verbose_name_plural = 'Categories'
ordering = ['title']
def __str__(self): # String views. If not be this parameters, be number vice world
return self.title
Since you've put 'get_photo' in NewsAdmin.read_only_fields and it is not a model field, it's supposed to be a method or a property in either News or NewsAdmin.
You should change it to 'photo' because read_only_fields only meant for fields to be non-editable.
class NewsAdmin(admin.ModelAdmin):
...
readonly_fields = ('photo', 'views', 'create_at', 'updated_at')
Try to add 'views' to list_display.
Probably a field can't be in read_only_fields unless it's shown in list_display.

Django rest framework create object with many-to-many filed serializer

I can't create a project object with many-to-many field to languages model. I need to find the best way to implement this. I have tried the django rest framework docs, but it didn't work for me. Do the language objects need to be created before the project object or DRF will handle this? This problem occurs when I added the owner field, then I needed to add the create method inside the ProjectSerializer to save the object owner, but then this error occurred: Direct assignment to the forward side of a many-to-many set is prohibited. Use languages.set() instead.
I tried languages.set() but it still does not work.
models.py
from django.db import models
from django.contrib.auth.models import User
class Language(models.Model):
name = models.CharField(max_length=100, blank=True, default='')
description = models.TextField()
owner = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ['id']
def __str__(self):
return self.name
class Developer(models.Model):
name = models.CharField(max_length=100, blank=True, default='')
age = models.IntegerField()
bio = models.TextField()
created = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ['created']
def __str__(self):
return self.name
class Project(models.Model):
name = models.CharField(max_length=100, blank=True, default='')
stars = models.IntegerField()
developer = models.ForeignKey(Developer, related_name='projects', on_delete=models.CASCADE)
languages = models.ManyToManyField(Language)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ['stars']
def __str__(self):
return self.name
serializers.py
from rest_framework import serializers
from developers.models import Language, Developer, Project
class ProjectSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Project
fields = ['id', 'name', 'stars', 'developer', 'languages', 'owner', ]
def create(self, validated_data):
project = Project.objects.create(owner=self.context['request'].user, **validated_data)
return project
class LanguageSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
projects = ProjectSerializer(read_only=True, many=True)
class Meta:
model = Language
fields = ['id', 'name', 'description', 'projects', 'owner', ]
def create(self, validated_data):
language = Language.objects.create(owner=self.context['request'].user, **validated_data)
return language
class DeveloperSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
projects = ProjectSerializer(read_only=True, many=True)
class Meta:
model = Developer
fields = ['id', 'name', 'age', 'bio', 'projects', 'owner', ]
def create(self, validated_data):
developer = Developer.objects.create(owner=self.context['request'].user, **validated_data)
return developer

Django Rest Framework to return desired results from two models

I have two models (customer, movie) and I would like to return (movie_name, customer_name, id) when I hit the URL (api/customer/1) and when I hit the URL (api/customer/1/movies) just wanted the movie names alone. How can we achieve this ?
models.py
class Customer(models.Model):
name = models.CharField(max_length=200, null=True)
class Movie(models.Model):
movie_name = models.CharField(max_length=200, null=True)
customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
serializers.py
class CustomerSerializer(serializers.ModelSerializer):
class Meta:
model = Customer
fields = ('id', 'name')
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model = Movie
fields = '__all__'
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^api/customers/$', CustomerSerializer.as_view(), name='customers'),
]
Note:
At the moment, when I hit the URL (api/customers) it returns the id, name of all the customers. Now, I would like to know, when I hit the URL (api/customer/1) how to list the same information along with movie names and when I hit the URL (api/customer/1/movies) how to just return the movie names alone?
You will have to write two urls for this purpose but you can do this with one view and serializer like this
Urls
urlpatterns = [
path('admin/', admin.site.urls),
path('api/customers/<int:id>/', CustomerMovieView.as_view(check=True)),
path('api/customers/<int:id>/movies/', CustomerMovieView.as_view(check=False)),
]
Views and Serializers
from rest_framework import generics, response, serializer
class MovieSerializer(serializers.ModelSerializer):
customer_name = serializers.SerializerMethodField()
def get_customer_name(self, instance):
return instance.customer.name
class Mete:
model = Movie
fields = '__all__'
def to_representation(self, instance):
data = super().to_representation(instance)
if not self.context('check'):
data.pop('customer_name', None)
data.pop('customer', None)
return data
class CustomerMovieView(generics.GenericAPIView):
serializer_class = MovieSerializer
check = True
def get_serializer_context(self):
context = super().get_serializer_context()
context.update({'check': self.check})
return context
def get(self, request, *args, **kwargs):
id = kwargs.get('id')
movie = Movie.objects.get(id=id)
serialized = self.get_serializer(movie)
return response.Respoonse(serialized.data)

How to join two tables in django and serialize the same using one serializer?

I have been learning django and django rest framework since couple of weeks and I want to figure out how can I join two tables and serialize the data of same to return the json response using django rest framework.
I want to return result as json response:
{ 'user_id_id': 1, 'request_msg': 'Hi', 'response_msg': "Hi, Welcome" }
where result is
from django.db import connection
cursor = connection.cursor()
con = cursor.execute("SELECT backend_request_messages.user_id_id, backend_request_messages.request_msg as request_msg,backend_response_messages.response_msg as response_msg FROM backend_request_messages,backend_response_messages Where backend_request_messages.user_id_id=backend_response_messages.user_id_id=1 ")
Here is what I have tried :
#backend/Models.py
class User(models.Model):
username = models.CharField(max_length=50)
name = models.CharField(max_length=50, blank=True, null=True)
uid = models.CharField(max_length=12, blank=True, null=True)
age = models.CharField(max_length=3, blank=True, null=True)
active = models.BooleanField(default=True)
class Meta:
default_related_name = 'users'
def __str__(self):
return self.name
class Request_Messages(models.Model):
request_msg = models.CharField(max_length=100)
request_msg_created_at = models.DateTimeField(auto_now_add=True)
user_id = models.ForeignKey(
User, on_delete=models.CASCADE, null=True)
class Meta:
default_related_name = 'request_messages'
def __str__(self):
return self.request_msg
class Response_Messages(models.Model):
response_msg = response_msg = models.CharField(max_length=400)
response_msg_created_at = models.DateTimeField(auto_now_add=True)
user_id = models.ForeignKey(
User, on_delete=models.CASCADE, null=True)
class Meta:
default_related_name = 'response_messages'
def __str__(self):
return self.response_msg
#backend/serializers.py
class ListSerializer (serializers.Serializer):
user_id_id = serializers.IntegerField()
request_msg = serializers.CharField(max_length=100)
# request_msg_created_at = serializers.DateTimeField(read_only=True)
response_msg = serializers.CharField()
# response_msg_created_at = serializers.DateTimeField(read_only=True)
#backend/views.py
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Response_Messages, Request_Messages, User
from .serializers import ListSerializer
from django.db import connection
#api_view(['GET', 'POST'])
def chatbot(request):
if request.method == 'GET':
cursor = connection.cursor()
query_set = cursor.execute("SELECT backend_request_messages.user_id_id, backend_request_messages.request_msg as request_msg,backend_response_messages.response_msg as response_msg FROM backend_request_messages,backend_response_messages Where backend_request_messages.user_id_id=backend_response_messages.user_id_id=1 ")
columns = [column[0] for column in query_set.description]
results = []
for row in query_set.fetchall():
results.append(dict(zip(columns, row)))
serializer = ListSerializer(results)
return Response(serializer.data)
About serializers, You should refer to the docs (they're awesome and explain it best).
To give you a direction, I like to create a serializer for every model and if it's related to another model, I refer that in serializer, that way, You can easily customize behavior for each model (although not the only way at all).
So, about serializing I would do the following (notice my comments as well):
from django.contrib.auth.models import User
class User(User):
# Your user class, except, it should inherit Django's User/AbstractUser class.
class RequestMessages(models.Model):
request_msg = models.CharField(max_length=100)
request_msg_created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(
User, on_delete=models.CASCADE, null=True, related_name='requests_msg')
# NOTICE THE NEW RELATED NAME, WE'LL USE IT LATER.
class Meta:
default_related_name = 'request_messages'
def __str__(self):
return self.request_msg
class ResponseMessages(models.Model):
response_msg = response_msg = models.CharField(max_length=400)
response_msg_created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='responses_msg')
def __str__(self):
return self.response_msg
class RequestMsgSerializer(serializers.ModelSerializer):
# Specify what ever you like...
class Meta:
model = RequestMessages
fields = # Whatever you like to serialize.
class ResponseMsgSerializer(serializers.ModelSerializer):
class Meta:
model = ResponseMessages
fields = # Whatever you want serialized.
class UserSerializer(serializers.ModelSerializer):
# Using required = False will cause that every time you create a user they don't have to own messages.
requests_msg = RequestMsgSerializer(many=False, required=False)
responses_msg = ResponseMsgSerializer(many=False, required=False)
class Meta:
model = User
field = # Same as above ..
About your query, using raw SQL in Django is rear, usually, in most cases the Django built-in ORM will do the job and usually faster and better than you.
In your case, if you'll call your query like this for exmaple:
query_set = User.objects.filter(user=request.user)
the QuerySet object created will hit the DB one for the user object and X queries for all the associated messages with said user, so expensive.
But no need for a custom query with joins and stuff like that, Django has prefetch_related and select_related.
exmaple:
query_set = User.objects.filter(user=request.user).prefetch_related('requests_msg')
will reduce all the queries made for request messages associated to a user to only one!
Recap:
I wrote a lot because I'm still learning this stuff myself self and if you teach others you got it!
Refer to DRF's docs about serializers (there's even a dedicated section for nested serializers) and API Views, they really great.
Refer to Django's docs about prefetch related, select related and queries in general, again, Amazing docs that cover everything.
Don't just copy my code or anyone else's, there's no problem with that, just make sure you understand it first if not, you're bound to get stuck with it again!

DRF use nested serializer to create key object instead of array

Context
Say we take this example from the DRF relations guide.
# models.py
class Album(models.Model):
album_name = models.CharField(max_length=100)
artist = models.CharField(max_length=100)
class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
order = models.IntegerField()
title = models.CharField(max_length=100)
duration = models.IntegerField()
class Meta:
unique_together = ('album', 'order')
ordering = ['order']
def __str__(self):
return '%d: %s' % (self.order, self.title)
Using a serializer will get us this output
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.StringRelatedField(many=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
Will get us this output:
{
'album_name': 'Things We Lost In The Fire',
'artist': 'Low',
'tracks': [
'1: Sunflower',
'2: Whitetail',
'3: Dinosaur Act',
...
]
}
Question
How can i use the serializer to get the output like this:
{
'album_name': 'Things We Lost In The Fire',
'artist': 'Low',
'tracks': {
1: {order: 1, title: 'Sunflower'},
2: {order:2, title: 'Whitetail'},
3: {order:3, title: 'Dinosaur Act'},
...
}
}
This way we have an object with tracks instead of a numeric array. So i can do this.props.album.tracks[2].title this instead of this.props.album.tracks.find(track => track.order == 2}).title in javascript.
``I have an use case in where this seems to be more convenient in Reactjs.
What i have tried
I thought about overriding the to_representation method. But i see that this will get me an recursive loop.
class TrackSerializer(serializers.ModelSerializer):
def to_representation(self, instance):
print(self)
return '%s: { %s }' % (instance.order, self.to_representation(instance))
class Meta:
fields = '__all__'
model = Track
Furthermore i have searched and read the docs pretty well. But didn't find any solution for what i think should be a pretty logical solution to have out of the box. Making me think that i am wrong and missing something.
Thanks in advance.
Define a new TrackSerializer and use it in AlbumSerializer class as,
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ('id', 'order', 'title')
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
def to_representation(self, instance):
representation = super().to_representation(instance)
representation['tracks'] = {track['id']: track for track in representation['tracks']}
return representation

Resources