I have a cartmodel, cartitem and offlinecheckout model. I want to display cartitem instead of cartmodel id, I want to display all the cartitem data which have cart_id = offlinecheckout cart_id. But I got this response.
I tried a lot but didn't get. Anybody will please help me.
views.py
class GetAPI(APIView):
def get(self, request, *args, **kwargs):
serializer = OfflineSerializer()
return Response(serializer.data)
models.py
class OfflineCheckOut(models.Model):
billing_name = models.CharField(max_length=254)
billing_phone_no = models.CharField(max_length=15)
user = models.ForeignKey('accounts.User', on_delete=models.CASCADE)
cart = models.ForeignKey('cart.CartModel', on_delete=models.CASCADE)
cartitem = models.ManyToManyField(CartItem, blank=True)
# time_slot = models.ForeignKey('category.TimeSlot', on_delete=models.CASCADE)
address = models.ForeignKey('cart.CustomerAddress', on_delete=models.CASCADE)
status_choice = [
('0', 'Offline'),
('1', 'Online')
]
status = models.CharField(max_length=3, choices=status_choice, default=0)
# date = models.DateField()
date = models.DateField()
time_slot = models.ForeignKey('category.TimeSlot', on_delete=models.SET_NULL, null=True, blank=True)
order_id = models.CharField(max_length=254, blank=True)
# date = models.DateField()
razorpay_payment_id =models.CharField(max_length=254, blank=True)
razorpay_signature = models.CharField(max_length=254, blank=True)
paid = models.BooleanField(default=False)
service = models.ForeignKey('service.ServiceProvider', on_delete=models.SET_NULL, null=True, blank=True)
class CartModel(models.Model):
user = models.ForeignKey('accounts.User', on_delete=models.CASCADE)
status_choice = [
('1', 'open'),
('2', 'closed')
]
status = models.CharField(max_length=2, choices=status_choice, default=1)
validated = models.BooleanField(default=False)
def __str__(self):
return self.user.username
#property
def total_price(self):
return self.cartitem_set.aggregate(
total_price=Sum(F('quantity') * F('price'))
)['total_price'] or Decimal('0')
class CartItem(models.Model):
cart = models.ForeignKey('CartModel', on_delete=models.CASCADE)
user = models.ForeignKey('accounts.User', on_delete=models.CASCADE)
service = models.ForeignKey('accounts.SubCategory', on_delete=models.CASCADE)
defects = models.ForeignKey('category.Defects', on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
price = models.IntegerField()
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now_add=True)
order_placed = models.BooleanField(default=False)
serializers.py
class OfflineSerializer(serializers.ModelSerializer):
def total(self, obj):
return obj.total
total = serializers.IntegerField(read_only=True)
cartitems = CartItemSerializer( read_only=True, many=True)
class Meta:
model = OfflineCheckOut
fields = ['user', 'billing_name','billing_phone_no','cartitem', 'cartitems','cart', 'date', 'time_slot', 'address', 'total']
extra_fields = ['total', 'cartitems']
You have to put them in a serializer for CartModel. Then OfflineSerializer will use that for cart field.
class CartModelSerializer(serializers.ModelSerializer):
cartitem_set = CartItemSerializer(read_only=True, many=True)
class Meta:
model = CartModel
fields = [
"cartitems_set",
# other fields here
]
class OfflineSerializer(serializers.ModelSerializer):
def total(self, obj):
return obj.total
total = serializers.IntegerField(read_only=True)
cart = CartModelSerializer(read_only=True)
class Meta:
model = OfflineCheckOut
fields = ['user', 'billing_name','billing_phone_no','cartitem', 'cartitems','cart', 'date', 'time_slot', 'address', 'total']
extra_fields = ['total', 'cartitems']
EDIT: Changed the related name serializer from cartlineitems_set to cartlineitem_set
Related
I have my DRF app. In my case, one wallet can have many entries such as income or expense. When I call my endpoint (viewset) I get data in this format:
[
{
"id": "d458196e-49f1-42db-8bc2-ee1dba438953",
"owner": 1,
"viewable": [],
"entry": []
}
]
How can I get the content of "entry" variable?.
class Category(models.Model):
name = models.CharField(max_length=20, unique=True)
def __str__(self):
return self.name
class BudgetEntry(models.Model):
STATE= [
('income','income'),
('expenses','expenses'),
]
amount = models.IntegerField()
entry_type = models.CharField(max_length=15, choices=STATE, null=True)
entry_category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL)
class WalletInstance(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='owner', on_delete=models.CASCADE)
viewable = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='can_view', blank=True)
entry = models.ManyToManyField(BudgetEntry, related_name='BudgetEntry', blank=True)
Serializers.py:
class BudgetEntrySerializer(serializers.ModelSerializer):
class Meta:
model = BudgetEntry
fields = '__all__'
class WalletInstanceSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.id')
class Meta:
model = WalletInstance
fields = '__all__'
Views.py:
class WalletViewset(viewsets.ModelViewSet):
permission_classes = [IsAuthenticated]
serializer_class = WalletInstanceSerializer
def get_queryset(self):
user_id = self.request.user.id
available = WalletInstance.objects.filter(
Q(owner=user_id)
)
return available
Change your serializer like this:
class WalletInstanceSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.id')
entry = BudgetEntrySerializer(many=True, read_only=True)
class Meta:
model = WalletInstance
fields = '__all__'
I'm creating cart model in RESTful API project. For each product in request by using for statement I want to save each product, cauz in one request may appear more than one product in cart. Below is my
serializers.py:
from rest_framework import serializers
from main.serializers import ProductDetailsSerializer
from main.models import Cart, Product, CartProduct
# создаем сериализатор orderproduct
class CartProductSerializer(serializers.ModelSerializer):
class Meta:
model = CartProduct
fields = ('product', 'count')
class CartProductRepresentationSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(source='product.id')
title = serializers.CharField(source='product.title')
class Meta:
model = CartProduct
fields = ('id', 'title', 'price', 'count', 'product')
class AddProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('id')
class CartSerializer(serializers.ModelSerializer):
items = CartProductSerializer(many=True, write_only=True) # здесь мы добавляем этот продукт заказа
class Meta:
model = Cart
fields = ('count', 'items') # передаем все эти поля сюда
def get_total_cost(self, obj):
return obj.get_total_cost()
# здесь мы добавляем total cost (def get_total_cost(self. obj))
def create(self, validated_data):
request = self.context.get('request')
items = validated_data.pop('items')
cart = Cart.objects.create(**validated_data)
if request.user.is_authenticated:
cart.user = request.user
cart.save()
for product in items:
product = product['product']
# print(product)
product_id = request.GET.get('product')
CartProduct.objects.create(cart=cart, product_id=product_id, price=product.price, count=product['count'])
product.save()
def to_representation(self, instance):
representation = super().to_representation(instance)
representation['user'] = instance.user
representation['product'] = CartProductRepresentationSerializer(instance.products.all(), many=True, context=self.context).data
return representation
Here is the models. I create Cart and CartProduct for m2m field between Cart and Product
models.py
from django.db import models
from account.models import User
class Category(models.Model):
name = models.CharField(max_length=50 ,unique=True)
slug = models.SlugField(max_length=50 ,primary_key=True)
parent = models.ForeignKey('self', related_name='child', blank=True, null=True, on_delete=models.CASCADE)
def __str__(self):
if self.parent:
return f'{self.parent} -> {self.name}'
return self.name
class Product(models.Model):
category = models.ManyToManyField(Category)
title = models.CharField(max_length=250)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
author_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.title
class Comment(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
text = models.CharField(max_length=100)
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
def __str__(self):
return f"{self.author}: {self.text}"
class ProductImage(models.Model):
product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE)
image = models.ImageField(upload_to='products', null=True, blank=True)
class Cart(models.Model):
date_created = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=255, blank=True, null=True, default=False)
user = models.ForeignKey(User, related_name="carts", on_delete=models.CASCADE, blank=True, null=True)
count = models.PositiveIntegerField(default=1)
class CartProduct(models.Model):
product = models.ForeignKey(Product, related_name='products', on_delete=models.CASCADE)
cart = models.ForeignKey(Cart, related_name='cart', on_delete=models.CASCADE)
count = models.PositiveIntegerField(default=1)
price = models.DecimalField(max_digits=10, decimal_places=2, null=True)
Here is the views.py by using ModelViewSet I want to list all products in Cart
views.py
from rest_framework import viewsets
from cart.serializers import CartSerializer
from main.models import Cart
class CartViewSet(viewsets.ModelViewSet):
model = Cart
serializer_class = CartSerializer
def get_queryset(self,):
return Cart.objects.filter(user=self.request.user)
I'm have been struggling on this for 2 days, really. I want to populate Timesheet form field from Employees model as a select field / dropdown list.
Here are my files and I tried so far.
MODEL.PY
class Employees(models.Model):
# MONTHLY = 'MONTHLY'
# SEMIMONTHLY = 'SEMIMONTHLY'
# BIWKEEKLY = 'BIWKEEKLY'
# WEEKLY = 'WEEKLY'
# DAILY = 'DAILY'
PAY_PERIODS = [
('Monthly', 'Monthly'),
('Bi-weekly', 'Bi-weekly'),
('Weekly', 'Weekly'),
('Daily', 'Daily'),
]
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
is_active = models.BooleanField(default=True, verbose_name='Employee is actives')
first_name = models.CharField(max_length=50, verbose_name='First Name.', null=True, blank=False)
middle_name = models.CharField(max_length=50, verbose_name='Middle Name or Initials.', null=True, blank=True)
last_name = models.CharField(max_length=50, verbose_name='Last Name.', null=True, blank=False)
full_name = models.CharField(max_length=50, null=True, blank=True)
phone = PhoneField(blank=True, null=True)
email = models.EmailField(max_length=150, blank=True, null=True)
state = USStateField(null=True, blank=True)
street_address = models.CharField(max_length=150, blank=True, null=True, verbose_name='Street Address.')
zip_code = models.CharField(max_length=50, blank=True, null=True, verbose_name='Zip Code.')
hourly_rate = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
pay_frequency = models.CharField(max_length=100, choices=PAY_PERIODS, blank=True)
hire_date = models.TimeField(auto_now_add=True)
def __str__(self):
return self.full_name
def save( self, *args, **kwargs ):
self.full_name = f'{self.first_name} {self.middle_name} {self.last_name}'
super().save( *args, **kwargs )
class Timesheet(models.Model):
"""A timesheet is used to collet the clock-ins/outs for a particular day
"""
employer = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
full_name = models.ForeignKey(Employees, on_delete=models.CASCADE, null=True, blank=False, verbose_name='Select YOUR Name')
start_date = models.DateField(auto_now_add=True, null=True)
end_date = models.DateField(null=True, blank=False)
time_worked = models.DateField(null=True, blank=False)
def __str__(self):
return self.full_name
VIEWS.PY # I tried both function and class based views
class TimesheetView(CreateView):
model = Timesheet
fields = ('full_name', )
# form_class = TimesheetFrom
# queryset = Employees.objects.filter()
# print(queryset)
template_name = 'users/timesheet.html'
success_url = reverse_lazy('timesheet')
#login_required
def timesheet_view(request):
if request.method == 'POST':
form = TimesheetFrom(request.POST)
if form.is_valid():
emp = form.save(commit=False)
emp.user_id = request.user.pk
emp.save()
return redirect('dashboard')
else:
form = TimesheetFrom()
context = {
'form': TimesheetFrom(),
}
return render(request, 'users/timesheet.html', context)
FORM.PY
class TimesheetFrom(forms.Form):
class Meta:
model = Timesheet
fields = '__all__'
exclude = ('employer', )
#This is the current state of the form but I did tried many approaches.
I did search extensively here (Stackoverflow) but no use case for me. Any help will be greatly appreciated with a cup of coffee.
I have this situation:
Model Handling
class Handling(models.Model):
STATUS = (
('Active', 'Active'),
('Archived', 'Archived'),
)
entdate = models.DateTimeField(auto_now_add=True, null=True)
extdate = models.DateTimeField(auto_now_add=True, null=True)
kpallet = models.ForeignKey(Pallet, related_name='kpallet', null=True, on_delete= models.PROTECT)
kitem = models.ForeignKey(Item,related_name='kitems', null=True, on_delete= models.PROTECT, limit_choices_to={'kstatus': 'Active'})
quantity = models.SmallIntegerField(null=True)
kstatus = models.CharField(max_length=20, null=True, choices=STATUS)
def __str__(self):
return str(self.kpallet)
Model Item:
class Item(models.Model):
STATUS = (
('Active', 'Active'),
('Disabled', 'Disabled'),
('Archived', 'Archived'),
)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=50, null=True)
description = models.CharField(max_length=200, null=True)
kdimension = models.ForeignKey(Dimension, null=True, on_delete= models.PROTECT)
kclient = models.ForeignKey(Client, null=True, on_delete= models.PROTECT)
kstatus = models.CharField(max_length=20, null=True, choices=STATUS)
def __str__(self):
return self.name
Serializer:
class HandlingSerializer(serializers.ModelSerializer):
class Meta:
model = Handling
fields = '__all__'
Api:
#api_view(['POST'])
#permission_classes((permissions.AllowAny,))
def handlingCreate(request):
serializer = HandlingSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
else:
print(serializer.errors);
return Response("Error Handling not created")
return Response("Handling Created")
I get this error and i don't understand how to move on:
{'kitem': [ErrorDetail(string='Invalid pk "958c2fd2-bbb6-42d6-8bfe-fbe035e9ceb5" - object does not exist.', code='does_not_exist')]}
I've checked the pk and the object exists so I don't understand where the issue could be.
Thanks for your help in advance.
Fixed thanks to Blackdoor for the input.
This is the correct serializer:
class HandlingSerializer(serializers.ModelSerializer):
kitem = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all(), pk_field=serializers.UUIDField(format='hex_verbose'))
class Meta:
model = Handling
fields = '__all__'
use pk_field=UUIDField for PrimaryKeyRelatedField
class HandlingSerializer(serializers.ModelSerializer):
kitem = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all(), pk_field=UUIDField(format='hex'))
class Meta:
model = Handling
fields = '__all__'
hi i have 3 model name product, category, and categoryassin i want get 10 row from product object where category title is develop .
i did like this but it not work and i get error
class GetWebProductAPiView(APIView):
def get(self,request):
obj = Product.objects.filter(category__title = "develop")
serializer = ProductSerializer(instance=obj,many=True,context={'request': request})
return Response(serializer.data)
err:
Related Field got invalid lookup: title
how can in fix it?
this is my models
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True)
title = models.CharField(max_length=200)
video_length = models.CharField(max_length=20, null=True, blank=True)
mini_description = models.CharField(max_length=1000, null=True, blank=True)
full_description = models.TextField(null=True, blank=True)
you_need = models.CharField(max_length=1000, null=True)
you_learn = models.CharField(max_length=2000, null=True)
price = models.CharField(max_length=50, null=True, blank=True)
free = models.BooleanField(default=False)
video_level = models.CharField(max_length=100, null=True, blank=True)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
publish = models.BooleanField(default=False)
draft = models.BooleanField(default=False)
slug = models.SlugField(allow_unicode=True, null=True, blank=True)
image = models.FileField(upload_to=upload_to_custom_p, null=True, blank=True)
class Category(models.Model):
parent_id = models.IntegerField(null=True, blank=True)
title = models.CharField(max_length=200)
class CategoryAssin(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='product_id', related_name='category')
cat_id = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='categoryid')
and this is related serilizers
class CategorySerializer(ModelSerializer):
class Meta:
model = Category
fields = [
'id',
'parent_id',
'title',
]
read_only_fields = ['id']
class CategoryAssinSeralizer(ModelSerializer):
product = serializers.SerializerMethodField()
def get_product(self, obj):
return obj.product.title
cat_name = serializers.SerializerMethodField()
def get_cat_name(self, obj):
return obj.cat_id.title
class Meta:
model = CategoryAssin
fields = [
'cat_id',
'cat_name',
'product',
]
read_only_fields = ['id']
# product
class ProductSerializer(ModelSerializer):
product_ratings = ProductRatingsSerializer(many=True, read_only=True)
product_discount = ProductDiscountControllSerializer(read_only=True)
product_video = ProductWithoutVideoSerializer(many=True, read_only=True)
author = serializers.SerializerMethodField()
base64_image = serializers.SerializerMethodField(read_only=True, allow_null=True)
def get_author(self, obj):
return obj.author.first_name + ' ' + obj.author.last_name
category = CategoryAssinSeralizer(many=True)
url = main_page_post
class Meta:
model = Product
fields = [
'product_id',
'url',
'author',
'title',
'mini_description',
'you_learn',
'you_need',
'full_description',
'price',
'free',
'video_level',
'video_length',
'created_date',
'updated_date',
'product_ratings',
'product_discount',
'product_video',
'image',
'slug',
'draft',
'publish',
'category',
'base64_image',
]
read_only_fields = ['product_id',
'created_date',
'updated_date',
'author',
'base64_image',
'product_ratings',
'product_discount',
]
Add this in you view:
prod_ids = CategoryAssin.objects.filter(cat_id__title='develop').values_list('product', flat=True)
obj = Product.objects.filter(product_id__in=prod_ids)