I have a model that contains the newly added ListField class in DRF.
I am trying to store a List of strings so the output would look like so:
{
"hashtags":["something", "new"],
}
I'm pretty new to working with DRF but I seem to be having some trouble serializing the result. When I run the request I received a
HashField() is not JSON serializable error. Again I'm new to working with the the framework and Python in general but any suggestions, point in the right direction would be a help.
models.py
class HashField(serializers.ListField):
child = serializers.CharField(max_length=100)
class Mention(models.Model):
author = models.ForeignKey(User)
hashtags = HashField()
placename = models.CharField(max_length=140, default='SOME STRING')
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.placename
serializers.py
class MentionSerializer(serializers.ModelSerializer):
class Meta:
model = Mention
Django REST Framework has different kind of serializers, what you need here is a field serializer that validates a list type.
in serializers.py do as follow:
class MentionSerializer(serializers.ModelSerializer):
hashtags = serializers.ListField()
class Meta:
model = Mention
Related
I have created a project API in djangorestframework but I want to add a comments feature in it also. I was scratching my head thinking how can I do it but couldn't end up with a solution since I'm a beginner in djangorestframework.
here is my models.py:
class Project(models.Model):
title = models.CharField(max_length=300)
body = models.TextField(max_length=5000)
header_image = models.ImageField(default="default.jpg")
demo = models.URLField(null=True, blank=True)
code = models.URLField(null=True, blank=True)
and here is my serializers.py:
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = "__all__"
and here is my views.py:
#api_view(["GET"])
def getProjects(request):
project = models.Project.objects.all()
serializer = ProjectSerializer(project, many=True)
return Response(serializer.data)
Please help me in showing how can I add a comments section to the project API
note: I don't want the comments API to be a different object instead it should be a nested object in the object of the project
As each project can have several comments, you should implement Comment model and make a FK between these two
models.py
...
class Comment(models.Model):
project = models.ForeignKey('Project', related_name='comments', on_delete=models.CASCADE)
text = models.TextField(null=False, blank=False)
... # Some other field if you want. like created_time, author, ...
Then you can have a nested serializer to get comments with project:
serializers.py
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ('text', ...)
class ProjectSerializer(serializers.ModelSerializer):
comments = CommentSerializer(many=True)
class Meta:
model = Project
fields = (..., 'comments')
I have three models like those:
class Ambulance(models.Model):
ambulance_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
ambulance_name = models.CharField(max_length=255)
forms = models.ManyToManyField(Form)
class Form(models.Model):
form_id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
form_title = models.CharField(max_length=255)
class Page(models.Model):
page_id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
page_title = models.CharField(max_length=100, default='Untitled Page')
form = models.ForeignKey(
Form,
related_name='pages',
on_delete=models.CASCADE,
null=True
)
And the serializers as follow:
class AmbulanceSerializer(serializers.ModelSerializer):
forms = FormSerializer(read_only=True, many=True)
class Meta:
model = Ambulance
fields = ['ambulance_id', 'ambulance_name', 'forms']
class FormSerializer(ModelSerializer):
pages = PageSerializer(many=True, read_only=True)
class Meta:
model = Form
fields = ['form_id', 'form_title', 'pages']
class PageSerializer(ModelSerializer):
class Meta:
model = Page
fields = '__all__'
They were working and give me the nested object that I wanted but after adding many-to-many relationships, it gives me an internal server error 500 and it didn't tell me what the problem was, after debugging I found the problem occurs when calling AmbulanceSerializer(ambulance) or FormSerializer(form)
Could someone give me some hint? and what the problem actually!
Your code is wrong:
Can you please check this line?
fields = fields = ['ambulance_id', 'ambulance_name', 'forms']
which is wrong syntax.
You can try with this:
fields = ['ambulance_id', 'ambulance_name', 'forms']
Following your comment, where you state that you are using these serializers for "all types of requests", the answer is simple: remove read_only=True whenever you are using a nested serializer.
The read_only parameter will stop writes i.e. POST, PUT, etc... requests.
I am trying to create form using this model. I want to add data in this database model using form to perform CRUD operation. I am using MySQL database.
models.py
from django.db import models
from .managers import CategoryManager, SubCategoryManager
# this is my parent model
class Node(models.Model):
name = models.CharField(max_length=150)
parent = models.ForeignKey(
'self',
on_delete=models.CASCADE,
related_name='children',
null=True,
blank=True
)
def __str__(self):
return self.name
class Meta:
ordering = ('name',)
verbose_name_plural = 'Nodes'
class Category(Node):
object = CategoryManager()
class Meta:
proxy = True
verbose_name_plural = 'Categories'
class SubCategory(Node):
object = SubCategoryManager()
class Meta:
proxy = True
verbose_name_plural = 'SubCategories'
class Product(models.Model):
sub_category = models.ForeignKey(
SubCategory, on_delete=models.CASCADE
)
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
def __str__(self):
return self.name
Try the Imagine smart compiler which allows automatic generating of code + tests for your CRUD APIs and Django models from a very simple config. Amongst other things, it generates code in the correct way to handle foreign key relationships in Django Views. You can also try a demo here imagine.ai/demo
PS: Something like this simple config will generate all the code for the CRUD API along with the tests!
Model Node {
id integer [primary-key]
name string [max-length 150]
}
Model Product {
id integer [primary-key]
name string [max-length 100]
description string [nullable]
}
I have looked at this submission and there is so much clutter in the code I am having a hard time following it: Pass a custom queryset to serializer in Django Rest Framework
Now currently, I am trying to write a serializer that returns a list of all the cities in my table of venues. There may be many venues in each city, but I only want to return the city name once.
I know I need to create a custom model manager for this to modify the queryset, but I am unsure how to pass it to the serializer. I am rather lost in documentation and example. Do I need to write sql do I not? This is why not having a mentor really is a pain.
what I have so far.
models.py:
class Venue(models.Model):
name = models.CharField(max_length=150, blank=False)
description = models.CharField(max_length=1000)
image = models.ImageField(upload_to=imgUnique('venueMedia/venueImages'))
streetAddress= models.CharField(max_length=100)
city = models.CharField(max_length=100, blank=False)
state = models.CharField(max_length=100, blank=False)
serializers.py:
from rest_framework import serializers
from models import Venue, Room
class citySerializer(serializers.Serializer):
and my custom model in models.py:
class CityListManager(models.Manager):
def get_query_set(self):
return super(CityListManager, self).get_query_set().filter
All of the code is incomplete as I figure this out and put it all together
so looks like I was doing it wrong in the first place here is the working code
# queryset for cityListView
def getcityList():
cityList = Venue.objects.raw("""SELECT DISTINCT city
FROM Venue""")
return cityList
class citySerializer(serializers.ModelSerializer):
class Meta:
model = Venue
fields = 'city'
read_only_fields = 'city'
class cityListViewSet(viewsets.viewSet):
def list(self, request):
queryset = getcityList()
serializer = citySerializer(queryset, many=True)
return Response(serializer.data)
I have pretty simple and obvious question that i am trying to search for a while now.
I have a model, Picture, that has foreign keys like created_by, Province, and City.
What I want is to get all model fields serialized to json.
Models.py:
class Picture(models.Model):
name = models.TextField("Title", max_length=10000, null=True, blank=True)
meta_data = models.TextField("meta_data", null=True, blank=True)
created_by = models.ForeignKey(User, related_name="created_by")
city = models.ForeignKey(City, null=True, blank=True)
pro = models.ForeignKey(Province, verbose_name="Province")
class Province(models.Model):
name = models.CharField(max_length=50)
pi_meta_data = models.TextField(null=True, blank=True)
intro = models.CharField(max_length=1000, null=True, blank=True)
description = models.TextField(max_length=10000, null=True, blank=True)
class City(models.Model):
name = models.CharField(max_length=50)
pi_meta_data = models.TextField(null=True, blank=True)
intro = models.CharField(max_length=1000, null=True, blank=True)
description = models.TextField(max_length=10000, null=True, blank=True)
You can use Django Rest Framework, and serialize models with ease.
Your model serializers would be:
class PicturesSerializer(serializers.ModelSerializer):
class Meta:
model = Picture
# Only including fields in this case to explicitly show that
# every field in the Pictures model is serialized. In the rest of
# the Serializes fields will be left out for brevity.
fields = ("name", "meta_data", "created_by", "city", "pro")
class ProvinceSerializer(serializers.ModelSerializer):
class Meta:
model = Province
class CitySerializer(serializers.ModelSerializer):
class Meta:
model = City
Thats it. Seriously.
Everything is nicely packed into json for you, even if you change your models down the line.
But how easy is it to use the serialized data? A simple view using those serialized models would be:
class PicturesList(APIView):
"""
List all Pictures, or create a new Picture.
"""
def get(self, request, format=None):
pictures = Pictures.objects.all()
serializer = PicturesSerializer(pictures, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = PicturesSerializer(data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
The documentation is literally amazing. They have a cool tutorial to get you started. They even have a sweet browseable api that lets you visually navigate through your api.
There is a "Django Full Serialization" module which is part of wadofstuff which can serialize related objects among other things. This answer https://stackoverflow.com/a/3753769/187729 has more info.