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?
Try to inherit from ModelSerializer instead of Serializer
class IndustriCategoria(serializers.ModelSerializer):
class Meta:
model = IndustriaCategoria
fielst = ('__all__')
Related
I'm starting a project in django 4.1. and I run into this problem:
many to many relationship: I have a field of this type that is required, and everything is fine, but when I use the filter_horizontal it does not let me insert the chosen value, it tells me that it is required, however I am selecting values
Admin.py:
from django.contrib import admin
from .models import *
from django.contrib.auth.models import User
class CatalejoAdmin(admin.ModelAdmin):
filter_horizontal = ('tematicas',)
admin.site.register(Catalejo, CatalejoAdmin)
admin.site.register(Tematicas)
Model:
from django.db import models
from django.contrib.auth.models import User
class Tematicas(models.Model):
tematica = models.CharField(max_length=500)
fecha = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User,null=True , default=User, editable=False, on_delete=models.DO_NOTHING)
class Meta:
ordering = ["tematica"]
verbose_name_plural = "Temática"
def __str__(self):
return self.tematica
class Catalejo(models.Model):
fecha = models.DateField()
titulo = models.CharField(max_length=500)
tematicas = models.ManyToManyField(Tematicas, related_name='Temáticas')
author = models.ForeignKey(User,null=True , default=User, editable=False, on_delete=models.DO_NOTHING)
fichero = models.FileField(upload_to='gestores/%Y/%m/%d', null=True, blank=True)
class Meta:
ordering = ["fecha"]
verbose_name_plural = "Catalejo"
def Tematicas(self):
return ",\n".join([p.tematica for p in self.tematicas.all()])
def dehydrate_full_title(self, Tematicas):
return '%s by %s' % (Tematicas.tematica)
enter image description here
I'm working on a small project using Django Rest Framework, I would like to access chatmessage_thread. I don't see chatmessage_thread in my result, should I add something in my serializer ?
This is my queryset:
class ThreadViewSet(viewsets.GenericViewSet):
queryset = Thread.objects.all()
serializer_class = ThreadSerializer
def list(self, request):
objectSerializer = self.serializer_class(Thread.objects.by_user(user=request.user).prefetch_related('chatmessage_thread').order_by('timestamp'), many=True)
return Response(objectSerializer.data)
This is my serializer:
from rest_framework import serializers
from chat.models import Thread
from datetime import date
class ThreadSerializer(serializers.ModelSerializer):
class Meta:
model = Thread
fields = '__all__'
depth = 1
should I add something to my Serializer?
This is my model:
from django.db import models
from django.contrib.auth import get_user_model
from django.db.models import Q
User = get_user_model()
class ThreadManager(models.Manager):
def by_user(self, **kwargs):
user = kwargs.get('user')
lookup = Q(first_person=user) | Q(second_person=user)
qs = self.get_queryset().filter(lookup).distinct()
return qs
class Thread(models.Model):
first_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_first_person')
second_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True,
related_name='thread_second_person')
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = ThreadManager()
class Meta:
unique_together = ['first_person', 'second_person']
class ChatMessage(models.Model):
thread = models.ForeignKey(Thread, null=True, blank=True, on_delete=models.CASCADE, related_name='chatmessage_thread')
user = models.ForeignKey(User, on_delete=models.CASCADE)
message = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
I need help please
Yes you need to add a serializer for ChatMessage and add that as a field to ThreadSerializer. Something like this:
class ChatMessageSerializer(serializers.ModelSerializer):
class Meta:
model = ChatMessage
fields = '__all__'
class ThreadSerializer(serializers.ModelSerializer):
chatmessage_thread = ChatMessageSerializer(many=True)
class Meta:
model = Thread
fields = '__all__'
depth = 1
Respect for everyone here.
I have CustomUser model from one app, and Field model from another app. And I put a connection in CustomUser model with Field model via ManyToMany.
Field is for interested fields, and in signup form I have input like "In What do you have interests?"
I can easily get other datas like username, date_of_birth, email... But cannot get this interests. It returns courses.Field.None
Here is the models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from courses.models import Field
class CustomUser(AbstractUser):
username = models.CharField(max_length=32 , verbose_name="Login", unique=True, )
first_name = models.CharField(max_length=64, verbose_name="Ismingiz", blank=False, null=False)
second_name = models.CharField(max_length=64, verbose_name="Familyangiz", blank=False, null=False)
# & dob = date of birth
dob = models.DateField(auto_now_add=False, verbose_name="Yoshingiz", blank=False, null=True)
gender_choices = [("e", "Erkak"), ("a", "Ayol")]
gender = models.CharField(choices=gender_choices, verbose_name="Jinsingiz", default="e", max_length=1)
-> interests = models.ManyToManyField(Field, verbose_name="Qiziqishlaringiz")
longitude = models.CharField(max_length=256, verbose_name="Yashash joyingiz (uzunlik)", null=True, blank=True)
latitude = models.CharField(max_length=256, verbose_name="Yashash joyingiz (kenglik)", null=True, blank=True)
And this is my views.py file from courses App
from django.shortcuts import render
from .models import Center
from .serializers import CenterSerializer, UserSerializer
from rest_framework import generics
from django.contrib.auth import get_user_model
from rest_framework.response import Response
from decimal import Decimal
from slugify import slugify
import operator
from rest_framework.decorators import api_view
...
other views here
...
def center_list(request):
if request.method == 'GET':
dorilar = Center.objects.all()
serializers = CenterSerializer(dorilar, many=True)
dorixonalar = []
uzunlik = request.GET.get('uz')
kenglik = request.GET.get('keng')
------> print(request.user.interests)
interests = request.GET.get('interest').split(",")
if uzunlik and kenglik:
uzunlik = Decimal(uzunlik)
kenglik = Decimal(kenglik)
location = Decimal(uzunlik + kenglik)
dorixonalar = yaqinlik_boyicha_filter(dorilar, location, interests)
serializers = CenterSerializer(dorixonalar, many=True)
return Response(serializers.data)
else:
return Response(serializers.data)
Thanks in advance. :)
request.user.interests is a Manager. You need to:
print(request.user.interests.all())
I have two models in my application. Here is my code in models.py:
from django.db import models
class TblDivision(models.Model):
strdivisionname = models.CharField(db_column='strDivisionName', max_length=35, blank=True, null=True) # Field name made lowercase.
class Meta:
db_table = 'Tbl_Division'
class TblPosition(models.Model):
strpositionname = models.CharField(db_column='strPositionName', max_length=30, blank=True, null=True) # Field name made lowercase.
class Meta:
db_table = 'Tbl_Position'
class TblEmployee(models.Model):
strname = models.CharField(db_column='strName', max_length=70, blank=True, null=True) # Field name made lowercase.
stremployeeid = models.CharField(db_column='strEmployeeID', max_length=10, blank=True, null=True) # Field name made lowercase.
bitactive = models.BooleanField(db_column='bitActive', blank=True, null=True) # Field name made lowercase.
intdivision = models.ForeignKey(TblDivision, db_column='intDivision',related_name='division', on_delete=models.CASCADE)
intposition = models.ForeignKey(TblPosition, db_column='intPosition',related_name='position', on_delete=models.CASCADE)
class Meta:
db_table = 'Tbl_Employee'
This is my code in serializer.py:
from rest_framework import serializers
from .models import TblEmployee,TblDivision
class DivisionSerializer(serializers.ModelSerializer):
class Meta:
model = TblDivision
fields=['id','strDivisionName']
class EmployeeSerializer(serializers.ModelSerializer):
division = DivisionSerializer(many=True, read_only=True)
class Meta:
model = TblEmployee
fields=['id','strname','stremployeeid','intdivision','division']
And this my views.py:
from .models import TblEmployee
from .serializer import EmployeeSerializer,DivisionSerializer
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
#api_view(["GET", ])
def api_list_employee_view(request):
try:
employee_list = TblEmployee.objects.all()
except TblEmployee.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == "GET":
serializer = EmployeeSerializer(employee_list, many="true")
dataEmployee = serializer.data
return Response(dataEmployee)
I want to create a simple API that shows data from Employee model and its division name in JSON Format. But the API doesn't show the strDivisionName field. It shows only field from Employee model. Can Anyone explain my problem and its solution? I'm still new in Django Rest Framewrok. Thank you before
Update your serializer with this code:
from rest_framework import serializers
from .models import TblEmployee,TblDivision
class DivisionSerializer(serializers.ModelSerializer):
class Meta:
model = TblDivision
fields=['id','strdivisionname']
In the fields, you showing the wrong field name. It's strdivisionname not strDivisionName.
my friend you made a mistake in your serializer code! you must provide exact same name you entered in your models (in models you wrote : 'strdivisionname' and in serializer : 'strDivisionName')
because you serialize your TblEmployee instance with EmployeeSerializer! and in your EmployeeSerializer there is not any strdivisionname fields! you must make a foreignKey from that in your models, am I right?
I have this model in django
from django.db import models
class ProductType(models.Model):
name = models.CharField(max_length=250)
slug = models.SlugField(unique=True)
def __unicode__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=250)
slug = models.SlugField(unique=True)
type = models.ForeignKey(ProductType, related_name='product_type')
related_products = models.ManyToManyField('self',blank=True,null=True)
description = models.TextField()
def __unicode__(self):
return self.name
What I would like to do is in the admin have the Products as tabular inline to a quote page that have multiple products. This thing is that the first selected model can be a parent to the others and therefore I would like the choices of the next elements to be sorted by the first.
this is the quote model
from django.db import models
from django.utils.translation import ugettext as _
import datetime
from products.models import Product
from customers.models import Customer
class Quote(models.Model):
quoteid = models.IntegerField(_('Quote ID'), max_length=8, unique=True, default=number)
slug = models.SlugField(unique=True,default=number)
add_date = models.DateTimeField(auto_now_add=True)
customer = models.ForeignKey(Customer, related_name='quote_customer',blank = True, null = True)
product = models.ManyToManyField(Product, related_name='quote_product')
def __unicode__(self):
return str(self.quoteid)
and the admin part
from django.contrib import admin
from quotes.models import Quote
class ProductInline(admin.TabularInline):
model = Quote.product.through
extra = 3
class QuoteAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('quoteid',)}
fieldsets = (
(('Quote'), {'fields': ('slug','quoteid','customer',)}),
)
list_display = ('quoteid','customer','add_date',)
inlines = [ ProductInline]
admin.site.register(Quote,QuoteAdmin)
I know this is quite tricky and I have tried many ways but I have not found a solution that works. I have tried with formfield_for_manytomany but I can't fully grasp how to return the first tabularinline object as the input for the queryset.
If someone have a link that explains a method to do this I would be grateful.