I'm still getting to know DRF but when I run the command serializer.data
it returns an empty set. Here is what I'm working with
models.py
import datetime
from django.db import models
from django.db.models.fields.related import ForeignKey
from django.utils import timezone
from accounts.models import CustomUser
class IndustriaCategoria(models.Model):
name = models.CharField(max_length=20, null=False, blank=False)
def __str__(self):
return self.name
class Post(models.Model):
category = models.ForeignKey(IndustriaCategoria, on_delete=models.CASCADE)
author = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
title = models.CharField(max_length=512, null=False, blank=False)
body = models.TextField()
timestamp = models.DateTimeField(default=timezone.now)
link = models.URLField(max_length=500, null=True)
ups = models.IntegerField(default=0)
score = models.IntegerField(default=0)
hotness = models.IntegerField(default=0)
serializers.py
from django.db.models import fields
from rest_framework import serializers
from .models import IndustriaCategoria, Empresa, Post, Comment
class IndustriaCategoria(serializers.Serializer):
class Meta:
model = IndustriaCategoria
fielst = ('__all__')
class PostSerializer(serializers.Serializer):
class Meta:
model = Post
fields = ('__all__')
I have a management command which creates some data so I can just start throwing commands. Here is where the problem comes up:
>>> from accounts.models import CustomUser
>>> from forum.models import IndustriaCategoria, Post
>>> from forum.serializers import PostSerializer, IndustriaCategoria
>>> u = CustomUser.objects.all().first()
>>> i = IndustriaCategoria.objects.all().first()
>>> post = Post(category=i, author=u, title='hello world', body='this is a test', link='https://helloworld.com')
>>> post.save()
>>> serializer = PostSerializer(post)
>>> serializer.data
{}
Any idea why I got an empty set instead of the serialized data with the proportionated data when created the Post object?
CodePudding user response:
Try to inherit from ModelSerializer instead of Serializer
class IndustriCategoria(serializers.ModelSerializer):
class Meta:
model = IndustriaCategoria
fielst = ('__all__')