DRF nested serializer - object has no attribute - django-rest-framework

I am a newbie with django rest framework and python. and it is first time I asking a question here. thanks for helps from now..
--------------my models
class defined_views(models.Model):
name = models.CharField(max_length=150)
class defined_permissions(models.Model):
name = models.CharField(max_length=150)
class menuler(models.Model):
adi= models.CharField(max_length=150, null=True)
sira= models.PositiveIntegerField(null=True, blank=True)
parentId= models.ForeignKey('self', null=True, on_delete=models.CASCADE)
viewId= models.ForeignKey(defined_views, null=True, on_delete=models.CASCADE)
menu_type= models.CharField(max_length=150, null=True)
class user_menu_permission(models.Model):
userId = models.ForeignKey(User, null=False, on_delete=models.CASCADE)
menuID = models.ForeignKey(menuler, null=False, on_delete=models.CASCADE)
permissionID = models.ForeignKey(defined_permissions, null=True, on_delete=models.CASCADE)
-------------------serializer
class menulerSerializer(serializers.ModelSerializer):
class Meta:
model = menuler
fields = ['id', 'adi', 'sira', 'parentId', 'viewId', 'menu_type']
class user_menu_permissionSerializer(serializers.ModelSerializer):
menu = menulerSerializer()
class Meta:
model = user_menu_permission
fields = ['menuID', 'permissionID', 'menu']
class UserSerializer(serializers.ModelSerializer):
menuler = user_menu_permissionSerializer(
source='user_menu_permission_set', many=True)
class Meta:
model = User
fields = ['id', 'username', 'menuler']
------------------and view
class userView(APIView):
def get(self, request):
queryset = User.objects.all()
serializer = UserSerializer(queryset, many=True)
return Response(serializer.data)
I get this errror
"Got AttributeError when attempting to get a value for field menu on serializer user_menu_permissionSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the user_menu_permission instance.
Original exception text was: 'user_menu_permission' object has no attribute 'menu'."
if I change user_menu_permissionSerializer like that
class user_menu_permissionSerializer(serializers.ModelSerializer):
class Meta:
model = user_menu_permission
fields = ['menuID', 'permissionID']
I get result like that bu I want get menu as tree also.. but unfortunetly...
[
{
"id": 1,
"username": "admin",
"menuler": []
},
{
"id": 2,
"username": "taner.kader",
"menuler": [
{
"menuID": 2,
"permissionID": 1
},
{
"menuID": 3,
"permissionID": 1
},
{
"menuID": 5,
"permissionID": 1
}
]
}
]

I have solved like below
models
class defined_views(models.Model):
name = models.CharField(max_length=150)
class defined_permissions(models.Model):
name = models.CharField(max_length=150)
class menuler(models.Model):
adi= models.CharField(max_length=150, null=True)
sira= models.PositiveIntegerField(null=True, blank=True)
parentId= models.ForeignKey('self', null=True, on_delete=models.CASCADE)
viewId= models.ForeignKey(defined_views, null=True, on_delete=models.CASCADE)
menu_type= models.CharField(max_length=150, null=True)
permissionID = models.ManyToManyField(defined_permissions, through='user_menu_permission')
userId = models.ManyToManyField(User, through='user_menu_permission')
class user_menu_permission(models.Model):
# userId = models.ForeignKey(User, related_name='kullanici_menuler', null=False, on_delete=models.CASCADE)
userId = models.ForeignKey(User, null=False, on_delete=models.CASCADE)
menuID = models.ForeignKey(menuler,null=False, on_delete=models.CASCADE)
permissionID = models.ForeignKey(defined_permissions, null=True, on_delete=models.CASCADE)
serializers
class defined_permissionsSerializer(serializers.ModelSerializer):
class Meta:
model = defined_permissions
fields = ['id', 'name']
class defined_viewsSerializer(serializers.ModelSerializer):
class Meta:
model = defined_views
fields = ['id', 'name']
class menulerSerializer(serializers.ModelSerializer):
class Meta:
model = menuler
fields = ['id', 'adi', 'sira', 'parentId', 'viewId', 'menu_type']
# fields = ['adi']
class user_menu_permissionSerializer(serializers.ModelSerializer):
# menu = menulerSerializer(many=True)
class Meta:
model = user_menu_permission
fields = ['menuID', 'permissionID']
class UserSerializer(serializers.ModelSerializer):
# menuler = user_menu_permissionSerializer(
# source='user_menu_permission_set', many=True)
# kullanici_menuler = user_menu_permissionSerializer(many=True)
kullanici_menuler= menulerSerializer(source='menuler_set', many=True)
class Meta:
model = User
fields = ['id', 'username', 'kullanici_menuler']
and result
[
{
"id": 1,
"username": "admin",
"kullanici_menuler": []
},
{
"id": 2,
"username": "tayfun.uzun",
"kullanici_menuler": [
{
"id": 2,
"adi": "Yapılacaklar Listesi",
"sira": 1,
"parentId": 1,
"viewId": 1,
"menu_type": "view"
},
{
"id": 3,
"adi": "Raporlamalar",
"sira": 2,
"parentId": 1,
"viewId": 2,
"menu_type": "view"
},
{
"id": 5,
"adi": "Süreç İşleyişleri",
"sira": 1,
"parentId": 4,
"viewId": 3,
"menu_type": "view"
}
]
}
]

Try below something like this:
serializer.py :
class user_menu_permissionSerializer(serializers.ModelSerializer):
menu = menulerSerializer(many=True)
class Meta:
model = user_menu_permission
fields = ['menuID', 'permissionID', 'menu']
views.py :
class userView(APIView):
def get(self, request):
data = User.objects.all()
serializer = UserSerializer(data, many=True)
return Response(serializer.data)

Related

Why list of related items is not showing in API?

Field list_items is not showing in the API request.
I want to create request to get TodoItem with list of ListItem objects related to TodoItem.
I tried to change types of list_items value to another, but it isn't working.
Response right now:
[
{
"id": 1,
"type": "L",
"title": "Some title",
"due_date": null,
"created_at": "2022-08-02T09:26:07.149081Z",
"text_value": "",
"url_value": ""
}
]
Response I need:
[
{
"id": 1,
"type": "L",
"title": "Some title",
"due_date": null,
"created_at": "2022-08-02T09:26:07.149081Z",
"text_value": "",
"url_value": ""
"list_items":[
Item #1,
Item #2,
]
}
]
models.py
class TodoItem(models.Model):
id = models.AutoField(primary_key=True)
type = models.CharField(max_length=1, choices=(
('T', 'String'), ('L', 'List'), ('U', 'URL')))
title = models.CharField(max_length=200, blank=False, null=False)
due_date = models.DateField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
text_value = models.TextField(blank=True, max_length=500)
url_value = models.URLField(blank=True) # TODO: add validator/test it
class ListItem(models.Model):
id = models.AutoField(primary_key=True)
value = models.CharField(max_length=100)
checked = models.BooleanField(default=False)
todo_item = models.ForeignKey(TodoItem, on_delete=models.CASCADE)
position = PositionField(default=0, unique_for_fields=('todo_item',))
serializers.py
class ListItemSerializer(serializers.ModelSerializer):
todo_item = serializers.PrimaryKeyRelatedField(
queryset=TodoItem.objects.all(), required=False, allow_null=True, default=None)
class Meta:
model = ListItem
fields = ['id', 'value', 'position', 'todo_item']
class TodoItemSerializer(serializers.ModelSerializer):
created_at = django_filters.DateFromToRangeFilter()
def get_list_items(self, obj):
return ListItemSerializer(many=True, read_only=True).data
class Meta:
model = TodoItem
fields = '__all__'
I think you need to set the related_name in the ForeignKey field.
class ListItem(models.Model):
...
todo_item = models.ForeignKey(TodoItem, on_delete=models.CASCADE, related_name = "list_items")
position = PositionField(default=0, unique_for_fields=('todo_item',))
Then in the serializer, you can set the list_items field.
class TodoItemSerializer(serializers.ModelSerializer):
created_at = django_filters.DateFromToRangeFilter()
list_items = ListItemSerializer(many= True, read_only = True)
class Meta:
model = TodoItem
fields = ('id', 'type', 'title', 'due_at', 'created_at', 'text_value', 'url_value', 'list_items', )

rest_framework access objects of ManyToManyField in intermediate model

I have a patient model. Each patient can have several "Medical Records" where choices come from models like "BodyPart" or "Medicin":
class Patient(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Examination(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class BodyPart(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Medicin(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class MedicalRecord(models.Model):
patient = models.ForeignKey('Patient', on_delete=models.CASCADE,)
examination = models.ForeignKey('Examination', on_delete=models.CASCADE)
part_of_body = models.ForeignKey('BodyPart', on_delete=models.CASCADE)
medicin = models.ManyToManyField('Medicin')
def __str__(self):
return self.patient.name
Using Inlines we can nicely add Records to each Patient:
class MedicalRecordAdmin(admin.TabularInline):
model = MedicalRecord
extra = 1
class PatientAdmin(admin.ModelAdmin):
model = Patient
inlines = [MedicalRecordAdmin,]
...
admin.site.register(Patient, PatientAdmin)
...
Where I'm failing is (already tried trough, serializers.StringRelatedField(many=True), etc.), how can I serialize these relations from the side of the Patient Model?
# view
class PatientViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = PatientSerializer
queryset = Patient.objects.all()
# serializer
class PatientSerializer(serializers.ModelSerializer):
class Meta:
model = Patient
fields = '__all__'
depth = 3
ends in:
[
{
"id": 1,
"name": "Bert"
}
]
## But I would expect something like:
[
{
"id": 1,
"name": "Bert",
"medical_records":[
[
{
"medicine": ["a","b","c"],
"body_part": "leg",
"examination": "x-ray"
}
],
[
{
"medicine": ["e","f","g"],
"body_part": "head",
"examination": "surgery"
}
],
]
}
]
You have to use a nested serializer and use source fields to achieve the desired result.
Nested relationships- DRF documentation
Somewhat like this :
class Patient(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Examination(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class BodyPart(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Medicin(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class MedicalRecord(models.Model):
patient = models.ForeignKey('Patient', on_delete=models.CASCADE, related_name='patient_med')
examination = models.ForeignKey('Examination', on_delete=models.CASCADE, related_name='examination_med')
part_of_body = models.ForeignKey('BodyPart', on_delete=models.CASCADE, relayted_name='part_of_body_med')
medicin = models.ManyToManyField('Medicin', related_name='medicin_med')
class MedicalRecordSerializer(serializers.ModelSerializer):
body_part = serializers.CharField(source='part_of_body.name', read_only=True)
examination = serializers.CharField(source='examination.name', read_only=True)
medicine = serializers.ListField(source='medicine.name', read_only=True)
class Meta:
model = MedicalRecord
fields = ('body_part', 'examination', 'medicine')
class PatientSerializer(serializers.ModelSerializer):
patient_med = MedicalRecordSerializer(many=True, read_only=True)
class Meta:
model = Patient
fields = '__all__'
depth = 3

Django Rest Framework Relationships Serialization

I am trying to get serialized data for the below model with foreign keys but in the output i am only getting the ids instead of the fields of the model associated with hyperlink.
I have tried getting all the fields of the Skills model using the commented lines in the profile serializer but no luck
models.py
class Profile(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
first_name = models.CharField(max_length=20, null=True)
last_name = models.CharField(max_length=20, null=True)
def __str__(self):
return 'Profile for user {}'.format(self.user.username)
class Skill(models.Model):
skill = models.CharField(max_length=20, null=True)
level = models.CharField(max_length=20, null=True)
user = models.ForeignKey(Profile, null=True,
on_delete=models.PROTECT, related_name='skills')
def __str__(self):
return '%s: %s: %s' % (self.user, self.skill, self.level)
serializer.py
class SkillSerializer(serializers.ModelSerializer):
class Meta:
model = Skill
fields = ('user', 'skill', 'level')
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
# skills = SkillSerializer(many=True, read_only=True) # serializes child model's data inside this model's data
# skills = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='skill-detail')
# skills = serializers.StringRelatedField(many=True)
# skills = serializers.HyperlinkedIdentityField( view_name = "skill-list", lookup_field = "user")
url = HyperlinkedIdentityField( view_name="profile-detail", lookup_field = "id")
# user = serializers.ReadOnlyField(source='user.username')
# pdb.set_trace()
model = Profile
fields = ['id', 'user', 'url', 'skills']
views.py
class ProfileList(generics.ListCreateAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
class ProfileDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
class SkillList(generics.ListCreateAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
class SkillDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
urls.py
path('profiles/', views.ProfileList.as_view(), name='profile-list'),
path('profiles/<int:pk>/', views.ProfileDetail.as_view(), name='profile-detail'),
path('skills/', views.SkillList.as_view(), name='profile-list'),
path('skills/<int:pk>/', views.SkillDetail.as_view(), name='skill-list'),
Output: http://127.0.0.1:8000/authenticator/profiles/
[ "id": 6,
"user": 4,
"url": "http://127.0.0.1:8000/authenticator/profiles/6/",
"skills": [
57,
55
],
]
Expected output:
[ "id": 6,
"user": 4,
"url": "http://127.0.0.1:8000/authenticator/profiles/6/",
"skills": [
{
"user": 6,
"skill": "ABC",
"level": "Beginner"
},
{
"user": 6,
"skill": "DEF",
"level": "Intermediate"
},
]
]
This should normally work with the following in serializer.py:
class ProfileSerializer(serializers.ModelSerializer):
skills = SkillSerializer(many=True, read_only=True) # serializes child model's data inside this model's data
url = HyperlinkedIdentityField( view_name="profile-detail", lookup_field = "id")
class Meta:
model = Profile
fields = ['id', 'user', 'url', 'skills']
So basically uncomment the line in which the ProfileSerializer is told to serialize the skills with your SkillsSerializers, such that the entire skill objects are included in the result instead of its IDs.
You can use the concept of nested serializer for the solution.
Create two serializer ProfileReadSerializer and ProfileWriteSerializer
serializers.py
class SkillSerializer(serializers.ModelSerializer):
class Meta:
model = Skill
fields = ('user', 'skill', 'level')
class ProfileReadSerializer(serializers.ModelSerializer):
skills = SkillSerializer(many=True, read_only=True)
url = HyperlinkedIdentityField( view_name="profile-detail", lookup_field = "id")
class Meta:
model = Profile
fields = ('id', 'user', 'url', 'skills')
class ProfileWriteSerializer(serializers.ModelSerializer):
skills = SkillSerializer(many=True)
class Meta:
model = Profile
fields = ('id', 'user', 'url', 'skills')
In views you simply can use ModelViewSet to make things easy and use get_serializer_class
views.py
from rest_framework.viewsets import ModelViewSet
class ProfileVewSet(ModelViewSet):
queryset = Profile.objects.all()
def get_serializer_class(self):
if self.request.method == 'POST' or self.request.method == 'PUT' or self.request.method == 'PATCH':
return ProfileWriteSerializer
else:
return ProfileReadSerializer
And at last if you are using ModelViewSet you need to change the urls.py
urls.py
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('profile', views.ProfileViewSet, base_name='profile')
urlpatterns = [
path('', include(router.urls))
]
I think this will solve your problem. Please have a look.

Create model with foreign key and return serialized response

I'm trying to create a new note via a POST request that looks like this: {content: "hello world", user: 1} with a response that looks like this: { id: 1, content: "hello world", user: { id: 1, first_name: "Homer", last_name: "Simpson" }.
After reading at the other foreign key questions I've been able to create the note and get back something like: { id: 1, content: "hello world", user: 1 } but I really need the additional user information.
I attempted to modify the response using the to_representation like so:
class NotePOSTSerializer(serializers.ModelSerializer):
class Meta:
model = Note
fields = ('id', 'content', 'timestamp', 'user')
def to_representation(self, instance):
rep = super().to_representation(instance)
"""Convert `status` to human-readable."""
rep['user'] = UserSerializer(id=rep['user'])
return rep
but I got this error: TypeError: Object of type ModelState is not JSON serializable
This is what I've got so far. Thanks in advance!
models.py
class Article(models.Model):
id = models.PositiveSmallIntegerField('Article Id', null=True)
title = models.CharField('Title', max_length=100)
content = models.TextField('Description', blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
class Note(models.Model):
id = models.PositiveSmallIntegerField('Note Id', null=True)
content = models.TextField('Content', blank=True)
timestamp = models.DateTimeField('Timestamp', auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
views.py
class ArticleListView(viewsets.ModelViewSet):
serializer_class = ArticleSerializer
queryset = Article.objects.all()
class NoteListView(viewsets.ModelViewSet):
serializer_class =NoteSerializer
queryset = Note.objects.all()
def get_serializer_class(self):
assert self.serializer_class is not None, (
"'%s' should either include a `serializer_class` attribute, "
"or override the `get_serializer_class()` method."
% self.__class__.__name__
)
if self.request.method in ('POST', 'PUT'):
return NotePOSTSerializer
else:
return self.serializer_class
serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'first_name', 'last_name', 'email')
class NoteSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = Note
fields = ('id', 'content', 'timestamp', 'user')
class NotePOSTSerializer(serializers.ModelSerializer):
class Meta:
model = Note
fields = ('id', 'content', 'timestamp', 'user')
class ArticleSerializer(serializers.ModelSerializer):
notes = NoteSerializer(many=True, read_only=True)
class Meta:
model = Article
fields = ('id', 'title', 'content', 'created', 'updated', 'notes')
I'm getting completely different errors, so I will just provide working code
def to_representation(self, instance):
rep = super().to_representation(instance)
rep['user'] = UserSerializer(instance=User.objects.get(pk=instance.user_id)).data
# UserSerializer(instance=instance)
return rep

Django REST Framework: set required field in serializer but not in model

I have a model like this:
class Photo(models.Model):
dt_creation = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(Author, null=True, blank=True)
filename = models.CharField(max_length=255, db_index=True)
original_width = models.PositiveIntegerField()
original_height = models.PositiveIntegerField()
How can I set author field required only in serializer?
You can use extra_kwargs in class Meta:
class Meta:
model = Photo
fields = '__all__'
extra_kwargs = {'author': {'read_only': True, 'required': False}}

Resources