Using the same StreamField multiple times within a MultiFieldPanel - wagtail

I have divided a page into sections and I'm trying to use the same StreamField so I don't repeat code but having the same one in different MultiFieldPanel's as per my code below makes it not save correctly, after saving draft or publishing the page the fields go blank.
I'm trying to figure out the correct way to set this up.
top_heading = models.CharField(max_length=50, null=True, blank=True)
middle_heading = models.CharField(max_length=50, null=True, blank=True)
bottom_heading = models.CharField(max_length=50, null=True, blank=True)
center_cards = StreamField([
('centercardsblock', general_blocks.CenterCardsBlock()),
],
block_counts={
'centercardsblock': {'max_num': 4},
},
null=True,
blank=True,
use_json_field=True,
)
content_panels = Page.content_panels + [
MultiFieldPanel(
[
FieldPanel('top_heading'),
FieldPanel('center_cards'),
],
heading='Top Section'
),
MultiFieldPanel(
[
FieldPanel('middle_heading'),
FieldPanel('center_cards'),
],
heading='Middle Section'
),
MultiFieldPanel(
[
FieldPanel('bottom_heading'),
FieldPanel('center_cards'),
],
heading='Bottom Section'
),
]
I'm guessing the below will work but I want to try not repeat code.
top_center_cards = StreamField([
('centercardsblock', general_blocks.CenterCardsBlock()),
],
block_counts={
'centercardsblock': {'max_num': 4},
},
null=True,
blank=True,
use_json_field=True,
)
middle_center_cards = StreamField([
('centercardsblock', general_blocks.CenterCardsBlock()),
],
block_counts={
'centercardsblock': {'max_num': 4},
},
null=True,
blank=True,
use_json_field=True,
)
bottom_center_cards = StreamField([
('centercardsblock', general_blocks.CenterCardsBlock()),
],
block_counts={
'centercardsblock': {'max_num': 4},
},
null=True,
blank=True,
use_json_field=True,
)

You do need one StreamField declaration for each time the StreamField appears on the page. However, if you don't want to repeat the block definition, you can define that as a subclass of StreamBlock:
class CenterCardsStreamBlock(blocks.StreamBlock):
centercardsblock = general_blocks.CenterCardsBlock()
class Meta:
block_counts = {
'centercardsblock': {'max_num': 4},
}
and then use that in the StreamField definition rather than repeating the list.
top_center_cards = StreamField(
CenterCardsStreamBlock(),
null=True, blank=True, use_json_field=True
)
middle_center_cards = StreamField(
CenterCardsStreamBlock(),
null=True, blank=True, use_json_field=True
)
bottom_center_cards = StreamField(
CenterCardsStreamBlock(),
null=True, blank=True, use_json_field=True
)

Related

hi how can i put the images in my django project

how can i put the images in my django project, i have already installed pillow but when i try to save the images in the admin page it doesn't work and it doesn't show up in my detailed page, it just displays as text. I don't know what to do please help me solve this. THANKS IN ADVANCE
type here
my models file is there
from django.db import models
from django.core.validators import *
# Create your models here.
class Acueil(models.Model):
image = models.ImageField(blank=True)
class Animal(models.Model):
class Classe(models.TextChoices):
OISEAU = 'OIS'
MAMIFERE = 'MAM'
INSECTE = 'INSE'
REPTILE = 'REP'
POISSON = 'POI'
AMPHIBIEN = 'AMPH'
class Habitat (models.TextChoices):
JUNGLE = 'JUN'
SAVANE = 'SAV'
MARAI = 'MAR'
OCEAN = 'OCE'
FERME = 'FERM'
MONTAGNE = 'MON'
name = models.CharField( max_length = 50)
classe = models.CharField(choices=Classe.choices, max_length = 10 )
cris = models.CharField(max_length=20)
cut = models.FloatField(validators= [MinValueValidator(1.00), MaxValueValidator(5000)])
poids = models.FloatField(validators= [MinValueValidator(0), MaxValueValidator(100000)])
mode_life = models.CharField(max_length=1000)
comportement = models.CharField(max_length=1000)
habitat = models.CharField(choices= Habitat.choices,max_length=10)
description = models.CharField(max_length=2000)
nutrution = models.CharField(max_length=1000)
life_durée = models.IntegerField(validators= [MinValueValidator(1), MaxValueValidator(1000) ])
colors = models.CharField(max_length=25)
image = models.ImageField(blank=True)
my templates are here
{% extends 'wild/animal_base.html' %} {% block content %}
<h1>{{animal.name}}</h1>
<h2>{{animal.image}}</h2>
<ul>
<li>Classe :{{ animal.get_classe_display }}</li>
<li>Cris :{{ animal.cris}}</li>
<li>Taille :{{ animal.cut}} CM</li>
<li>Poids :{{ animal.poids}} KG</li>
<li>Habitat :{{ animal.habitat}}</li>
<li>Durée de vie :{{ animal.life_durée }} ANS</li>
<li>Nutrition :{{ animal.nutrution }}</li>
<li>Couleur :{{ animal.colors}}</li>
</ul>
<p>Comportement :{{animal.comportement}}</p>
<p>Mode de vie : {{animal.mode_life}}</p>
Retour à la liste d'animaux
{%endblock%}
settings
"""
Django settings for puerta project.
Generated by 'django-admin startproject' using Django 4.1.4.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-&i5qs$pywed8%c(t$5#=qzk3#p-+ttet_a#g&fr5f4%pa-#qw+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'wild',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'puerta.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'puerta.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

How to include related models using Django Rest Framework ListAPIView

Having 2 models and i need a list, a single queryset of lists that will combine all related fields from the 2 models.
class Product(models.Model):
name = models.CharField(...)
price= models.Decimal(...)
image = models.ImageField(...)
description2 = models.TextField(....)
class Order(models.Model):
buyer = models.CharField(...)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
have it return something that includes the full related model. A queryset Lists of ORDER with this result
{
"id": 1,
"buyer": 1,
"product": 3,
"name": "Product 1",
"image": "url",
"price": 10.50
},
{
"id": 2,
"buyer": 2,
"product": 2,
"name": "Product 2",
"image": "url",
"price": 6.50
},
OR
{
"id": 1,
"buyer": 1,
"product": [
{
'id': 1,
'name': 'Product 1',
'image': "url",
'price': 10.50
}],
},
{
"id": 2,
"buyer": 2,
"product": [
{
'id': 2,
'name': 'Product 2',
'image': "url",
'price': 6.50
}],
}
Is this possible?
First, you need to define the serializer in serializers.py file.
from rest_framework import serializers
from .models import Product, Order
class ProductSerializer(serializers.ModelSerializer):
class Meta:
fields = "__all__"
model = Product
class OrderSerializer(serializers.ModelSerializer):
product = ProductSerializer(read_only = True)
class Meta:
fields = ("buyer", "product", )
model = Order
And then, you need to create the ListAPIView for Order in views.py file.
from rest_framework import generics, mixins
from .models import Order
from .serializers import OrderSerializer
class OrderView(mixins.ListModelMixin, generics.GenericAPIView):
queryset = Order.objects.all()
serializer_class = OrderSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
Last you need to add the api url in urls.py,
from .views import *
urlpatterns = [
path('orders', OrderView.as_view(), name="order")
]

Django Rest Framework GET request returning Unathorized on React Frontend

it's my first question of SO. please, point out where I need to clarify at any point.
Im building a django back-end, react front-end app. I have this view that returns a 401 response whenever I try to directly access it on the front-end, even when a user is logged in. I have access to my other views but this one. It works fine in the drf browsable API.
I'm using both Session and TokenAuthentication in my default authentication classes.
Here's my base settings.py
import os
from decouple import config
import datetime
ALLOWED_HOSTS = []
BASE_DIR =
os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir))
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'django.contrib.sites',
'rest_framework',
'rest_auth',
'rest_framework.authtoken',
'dj_rest_auth',
'allauth',
'allauth.account',
'allauth.socialaccount',
'corsheaders',
'djoser',
'dj_rest_auth.registration',
'channels',
'core'
]
SITE_ID = 1
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # Whitenoise Middleware
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'home.urls'
AUTH_USER_MODEL = 'core.User'
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER': 'core.serializers.UserSerializer'
}
ACCOUNT_ADAPTER = 'core.adapter.CustomAccountAdapter'
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
]
REST_FRAMEWORK = {
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.AllowAny',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
#'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
# 'dj_rest_auth.jwt_auth.JWTCookieAuthentication'
],
"DEFAULT_PARSER_CLASSES": ["rest_framework.parsers.JSONParser"],
}
REST_USE_JWT = False
# JWT_AUTH_COOKIE = 'core.auth'
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=1),
'USER_ID_CLAIM': 'id',
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.media',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
ASGI_APPLICATION = 'home.routing.application'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'build', 'static')
STATICFILES_DIRS = []
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
REDIS_URL = config('REDIS_URL', 'redis://localhost:6379')
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels.redis.core.RedisChannelsLayer',
'CONFIG': {'hosts': [REDIS_URL]},
},
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = False
DJOSER = {
'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}',
'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}',
'ACTIVATION_URL': '#/activate/{uid}/{token}',
'SEND_ACTIVATION_EMAIL': True,
'SERIALIZERS': {},
}
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = "username_email"
#ACCOUNT_EMAIL_VERIFICATION = "mandatory"
# OLD_PASSWORD_FIELD_ENABLED = True
# PASSWORD_RESET_TIMEOUT_DAYS = 1
# ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 2
Here's the view where I first noticed the error
class StoreDetailView(RetrieveAPIView):
# Should return an object of all the attributes of a store if request.user is owner of store
serializer_class = StoreSerializer
permission_classes = (IsAuthenticated, )
def get_object(self):
try:
user = self.request.user
return Store.objects.get(owner=user)
# store = Store.objects.get(owner=self.request.user)
# return store
except ObjectDoesNotExist:
raise Http404('This store was not found for this user')
Check if the session_id or token is being passed in the request's headers.
This article explains in great detail on how to use Token based authentication with DRF.
Check if you have implemented any of the permission_classes, the functions for permissions requests exactly, if you dont allow GET method, the user cant read the object.
Here's and example I have implemented for my custom permissions:
class IsBusinessOwnerOrReadOnly(BasePermission):
"""
The request is authenticated and is the same user as the business owner, or is a read-only request.
"""
def has_permission(self, request, view):
return bool(
request.method in SAFE_METHODS or
request.user and
request.user.is_authenticated
)
def has_object_permission(self, request, view, obj):
if not isinstance(obj, Business):
raise Exception('This object is not a Business class instance')
return request.method in SAFE_METHODS or obj.owner.pk == request.user.pk

Why I am getting a Server Error(500) in production?

I created an app with DjangoREST , React and Redux it is Deployed on Heroku , but I am getting a Server Error(500) . I used allauth for token Authentication . Every urls is working fine in development but not in production .
I am successfully getting a token by /rest-auth/login/ url and the token is also passed successfully in the headers as "Authorization" : Token token .
This the error I am getting also I console.log the error -
urls.py
from django.contrib import admin
from django.urls import path, include, re_path
from todo import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api/todos/', views.TodoList.as_view()),
path('api/todos/<int:pk>/', views.TodoDetail.as_view()),
path('rest-auth/', include('rest_auth.urls')),
path('rest-auth/registration/', include('rest_auth.registration.urls')),
path('api/user/', views.UserAPI.as_view()),
re_path(r'^', views.FrontendAppView.as_view())
]
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', 'dj-react-todo.herokuapp.com']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'todo',
'corsheaders' ,
'rest_framework',
'rest_framework.authtoken',
'rest_auth' ,
'allauth',
'allauth.socialaccount' ,
'allauth.account',
'rest_auth.registration',
]
SITE_ID = 1
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'backend.urls'
WSGI_APPLICATION = 'backend.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication'
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'build', 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = (
'content-type' ,
'xsrfheadername' ,
'xsrfcookiename',
'X-CSRFTOKEN'
)
CSRF_COOKIE_NAME = "XCSRF-TOKEN"
ACCOUNT_EMAIL_VERIFICATION = "none"
ACCOUNT_AUTHENTICATION_METHOD = 'username'
ACCOUNT_EMAIL_REQUIRED = False
views.py
class TodoList(APIView):
serializer_class = TodoSerializer
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
def get(self, request, format=None):
todos = Todo.objects.filter(user=request.user)
serializer = TodoSerializer(todos, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = TodoSerializer(data=request.data)
if serializer.is_valid():
serializer.save(user=request.user)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializers.py
from rest_framework import serializers
from .models import Todo
from django.contrib.auth.models import User
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = ('id', 'user', 'title', 'description', 'completed', 'deadline', 'crucial')
def create(self , validated_data):
return Todo.objects.create(**validated_data)
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email')
This is how I created my actionCreator to get all the todos created by a user -
import axios from 'axios' ;
import { ADD_TODO, FETCH_TODOS, DELETE_TODO, TOGGLE_CHECKBOX, CRUCIAL_TODO} from './types' ;
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "XCSRF-TOKEN";
axios.defaults.headers.post['Access-Control-Allow-Methods'] = 'PATCH, DELETE, POST, GET, OPTIONS';
export const getTodos = () => dispatch => {
const token = localStorage.getItem('token')
const config = {
'headers': {
'Authorization': `Token ${token}` ,
}
}
if (token){
axios.get('https://dj-react-todo.herokuapp.com/api/todos/', config)
.then(res => {
dispatch({
type: FETCH_TODOS ,
payload: res.data
});
})
.catch(err => console.log(err))
}
}
I don't understand why I am getting this error , I already pass the token and I am getting the authenticated user also through that token .
I checked the heroku logs and it is also showing 500 Server Error .

How to join 3 tables in query with Django, combined select related and prefetch_related

I have tree models
class Category(models.Model):
name = models.CharField(max_length=60)
class Product(models.Model):
description = = models.CharField(max_length=255)
category = models.ForeignKey(Category, related_name='products')
class Inventory(models.Model):
userReservation = models.ForeignKey(User)
Product=models.ForeignKey(Product related_name='products_reservation')
Quantity = models.IntegerField()
I want to get all product by category, with quantity registered in inventory, for the user and the product
{
"id": 1,
"name": "Corbata",
"products": [{
"id": 10,
"description": "shoes",
"quantitybyInventory": 3
},
{
"id": 9,
"description": "shirt",
"quantitybyInventory": 1
}]}
I have a view with this class
views.py
class inventoryList(generics.ListCreateAPIView):
queryset = Category.objects.prefetch_related('products')
serializer_class = CategorybyProductSerializer
def get_object(self):
queryset = self.queryset()
obj = get_object_or_404(queryset)
return obj
And my serializer
class CategorybyProductSerializer(serializers.ModelSerializer):
products = ProductSerializer(many=True)
class Meta:
model = Category
fields = ('id', 'name', 'products')
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('id', 'description')
but I can not show the amount of the inventory table
this query just show me it
{
"id": 1,
"name": "Corbata",
"products": [{
"id": 10,
"description": "shoes"
},
{
"id": 9,
"description": "shirt"
}
]
}
I use SerializerMethodField, and this post
class ProductbyUserSerializer(serializers.ModelSerializer):
quantitybyInventory = serializers.SerializerMethodField(read_only=True)
def get_quantitybyInventory(self, product):
return product.products_reservation.filter(userReservation = self.context['request'].user).count()
class Meta:
model = Product
fields = ('id', 'description', 'quantitybyInventory')

Resources