Cannot assign "OrderItem.product" must be a "Product" instance - python

I am trying to create a "create order" endpoint, i keep getting
Cannot assign "<django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7f50dad00f70>": "OrderItem.product" must be a "Product" instance.
heres my models
def product_images(instance, filename):
return f"product/{instance.product_name}/{filename}"
class Product(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=200, null=True, blank=True)
description = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
image = models.ImageField(
storage=MediaRootS3BotoStorage(),
upload_to="product_images",
null=True,
blank=True,
)
price = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
return self.name
def save(self, *args, **kw):
self.slug = slugify(f"{self.name}")
super(Product, self).save(*args, **kw)
# Ecommerce Models Store and Product
def store_images(instance, filename):
return f"{instance.store_name}/{filename}"
class Store(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=200, null=True, blank=True)
description = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
image = models.ImageField(upload_to="store_images", null=True, blank=True)
delivery_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
address = models.CharField(max_length=100, null=True, blank=True)
phone_number = models.CharField(max_length=100, null=True, blank=True)
products = models.ManyToManyField("Product", through="StoresProduct")
def __str__(self):
return self.name
def save(self, *args, **kw):
self.slug = slugify(f"{self.name}")
super(Store, self).save(*args, **kw)
class Cart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.ManyToManyField("Product", through="StoresProduct")
quantity = models.IntegerField(default=1)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.user.email
def get_total(self):
return self.product.price * self.quantity
class StoresProduct(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
seller = models.ForeignKey(Store, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
quantity = models.IntegerField(blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
cart = models.ForeignKey(
Cart,
on_delete=models.CASCADE,
related_name="products",
default=None,
null=True,
blank=True,
)
product = models.ForeignKey(
Product,
on_delete=models.CASCADE,
related_name="+",
default=None,
null=True,
blank=True,
)
def __str__(self):
return f"{self.product.name} - {self.seller.name}"
class Meta:
unique_together = ["product", "seller"]
OrderStatus = (
("Pending", "Pending"),
("Delivered", "Delivered"),
("Cancelled", "Cancelled"),
("Processing", "Processing"),
)
class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=100, choices=OrderStatus, default="Pending")
delivery_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
order_id = models.CharField(max_length=100, null=True, blank=True)
order_items = models.ManyToManyField("Product", through="OrderItem")
store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, blank=True)
def __str__(self):
return self.user.email + " - " + self.order_id
def get_random_order_id(self):
order_id = str(uuid.uuid4()).replace("-", "").upper()[:10]
return order_id
# create order id with random string
def save(self, *args, **kwargs):
if not self.order_id:
self.order_id = self.get_random_order_id()
super(Order, self).save(*args, **kwargs)
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
order = models.ForeignKey(Order, on_delete=models.CASCADE)
store = models.ForeignKey(Store, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.product.name
and my views.py
#create order with orderitems
#swagger_auto_schema(method="post", request_body=OrderSerializer)
#api_view(["POST"])
#permission_classes((permissions.AllowAny,))
#authentication_classes([TokenAuthentication])
def create_order(request):
"""
Creates an order then creates an orderitem
"""
user = request.user
serializer = OrderSerializer(data=request.data)
if serializer.is_valid():
serializer.save(user=user)
order_id = serializer.data["id"]
order = Order.objects.get(pk=order_id)
cart = user.cart_set.all()
for item in cart:
OrderItem.objects.create(
order=order,
product=item.product,
quantity=item.quantity,
)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#swagger_auto_schema(method="post", request_body=AddToCartSerializer)
#api_view(["POST"])
#permission_classes((permissions.AllowAny,))
#authentication_classes([TokenAuthentication])
def add_to_cart(request):
"""
Adds a product to cart
"""
user = request.user
serializer = AddToCartSerializer(data=request.data)
if serializer.is_valid():
serializer.save(user=user)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Basically, users should be able to add products from various stores to their cart and when they are done they should be able to order.
I can't seem to figure out what i am doing wrongly, if there's a better way to do this do tell.I'm guessing my approach is problematic

Related

AttributeError: 'Order' object has no attribute 'shipping'

Learning Django with Tutorial.
In the end of lesson I have error:
AttributeError: 'Order' object has no attribute 'shipping'.
I can't understand what's wrong.
Error in PyCharm Terminal
I understand that Order must have shipping attribute, but cant find where exactly looking that.
Sorry for bad english.
My project files:
checkout.html
from django.db import models
from django.contrib.auth.models import User
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
price = models.FloatField()
digital = models.BooleanField(default=False, null=True, blank=False)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
def __str__(self):
return str(self.id)
#property
def get_cart_total(self):
orderitems = self.orderitem_set.all()
total = sum([item.get_total for item in orderitems])
return total
#property
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum([item.quantity for item in orderitems])
return total
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_addet = models.DateTimeField(auto_now_add=True)
#property
def get_total(self):
total = self.product.price * self.quantity
return total
class ShippingAddress(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
address = models.CharField(max_length=200, null=False)
city = models.CharField(max_length=200, null=False)
state = models.CharField(max_length=200, null=False)
zipcode = models.CharField(max_length=200, null=False)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.address
views.py
from django.shortcuts import render
from django.http import JsonResponse
import json
import datetime
from .models import *
def store(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
items = []
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
cartItems = order['get_cart_items']
products = Product.objects.all()
context = {'products':products, 'cartItems':cartItems}
return render(request, 'store/store.html', context)
def cart(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
items = []
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
cartItems = order['get_cart_items']
context = {'items':items, 'order':order, 'cartItems':cartItems}
return render(request, 'store/cart.html', context)
def checkout(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
items = []
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
cartItems = order['get_cart_items']
context = {'items':items, 'order':order, 'cartItems':cartItems}
return render(request, 'store/checkout.html', context)
def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print('Action', action)
print('productId', productId)
customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
if action == 'add':
orderItem.quantity = (orderItem.quantity + 1)
elif action == 'remove':
orderItem.quantity = (orderItem.quantity - 1)
orderItem.save()
if orderItem.quantity <=0:
orderItem.delete()
return JsonResponse('Item was added', safe=False)
def processOrder(request):
transaction_id = datetime.datetime.now().timestamp()
data = json.loads(request.body)
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
total = float(data['form']['total'])
order.transaction_id = transaction_id
if total == float(order.get_cart_total):
order.complete = True
order.save()
if order.shipping == True:
ShippingAddress.objects.create(
customer=customer,
order=order,
address=data['shipping']['address'], #порядок как в models
city=data['shipping']['city'],
state=data['shipping']['state'],
zipcode=data['shipping']['zipcode'],
)
else:
print('User is not logged in...')
return JsonResponse('Payment complete!', safe=False)
models.py
from django.db import models
from django.contrib.auth.models import User
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
price = models.FloatField()
digital = models.BooleanField(default=False, null=True, blank=False)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
def __str__(self):
return str(self.id)
#property
def get_cart_total(self):
orderitems = self.orderitem_set.all()
total = sum([item.get_total for item in orderitems])
return total
#property
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum([item.quantity for item in orderitems])
return total
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_addet = models.DateTimeField(auto_now_add=True)
#property
def get_total(self):
total = self.product.price * self.quantity
return total
class ShippingAddress(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
address = models.CharField(max_length=200, null=False)
city = models.CharField(max_length=200, null=False)
state = models.CharField(max_length=200, null=False)
zipcode = models.CharField(max_length=200, null=False)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.address
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.store, name="store"),
path('cart/', views.cart, name="cart"),
path('checkout/', views.checkout, name="checkout"),
path('update_item/', views.updateItem, name="update_item"),
path('process_order/', views.processOrder, name="process_order"),
]
I reviewed the lesson several times, code seems to be without mistakes.
Server side error
The error is because you didn't declared shipping variable in your Orders model.
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
shipping = models.CharField(max_length=200, null=True)
def __str__(self):
return str(self.id)
#property
def get_cart_total(self):
orderitems = self.orderitem_set.all()
total = sum([item.get_total for item in orderitems])
return total
#property
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum([item.quantity for item in orderitems])
return total
Go to models file and update the Order class with above code.
client side
While making API request set the header Content-Type to text/html.
Because the API is responding HTML file not json.
That's why you have an error in browser.
in Order model there should be a field named shipping which is require in the processorder view.
just add below field in Order model
shipping = models.BooleanField(default=False)
since you want ot hide it , then a property need to be added not the db field
so your model should look like this
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
#property
def shipping(self):
shipping = False
# add shipping logic here
return shipping
def __str__(self):
return str(self.id)
#property
def get_cart_total(self):
orderitems = self.orderitem_set.all()
total = sum([item.get_total for item in orderitems])
return total
#property
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum([item.quantity for item in orderitems])
return total
follow the tutorial a little more, you will be able to grasp the solution.

Cannot assign "'Sample Category'": "Product.category" must be a "Category" instance

While creating new products I'm getting such kind of error. Can someone help me?
class Product(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
name_geo = models.CharField(max_length=200, null=True, blank=True)
image = models.ImageField(null=True, blank=True, default='/placeholder.png')
brand = models.CharField(max_length=200, null=True, blank=True)
category = models.ForeignKey(Category, null=False, default=0, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
countInStock = models.IntegerField(null=True, blank=True, default=0)
createdAt = models.DateTimeField(auto_now_add=True)
_id = models.AutoField(primary_key=True, editable=False)
def __str__(self):
return self.name_geo
class Category(models.Model):
_id = models.AutoField(primary_key=True, editable=False)
name = models.CharField(max_length=200, null=True, blank=True)
createdAt = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
#api_view(['POST'])
def createProduct(request):
user = request.user
product = Product.objects.create(
user=user,
name_geo="Sample Name",
category="Sample Category",
price=0,
brand='Sample Brand',
countInStock=0,
)
serializer = ProductSerializer(product, many=False)
return Response(serializer.data)
Without separating category class in models.py everything works fine. I mean If i didn't use ForeignKey in Products class for category
It just has to be a Category Instance/Object
product = Product.objects.create(
user=user,
name_geo="Sample Name",
category=Category.objects.get_or_create(name="Sample Category"),
price=0,
brand='Sample Brand',
countInStock=0,
)
Notes:
You could just do a .get() or a .filter().first() if you don't want to create
If you use a form, you can get away with just the Category's PK/_id in the POST
this type of thing: f = form(request.POST) f.is_valid() f.save()
At the end that field will hold the PK/_id/Row# of the Category Obj

How to show FK fields in admin? DJANGO

I'm developing an e-commerce site and I'm trying to show in my ADMIN the 'produto_nome' related in my 'Ordem' table. For now, in my admin, in the 'Ordem' table, it's just showing the id of each object. Is it possible to show field 'produto_nome' in that 'Ordem' table ?
Below is my models
class Categoria(models.Model):
nome = models.CharField(max_length=50)
def __str__(self):
return self.nome
class Produto(models.Model):
produto_nome = models.CharField(max_length=70)
preco = models.IntegerField()
quantidade_em_estoque = models.IntegerField()
quantidade_vendida = models.IntegerField()
categoria = models.ForeignKey(Categoria, on_delete=models.CASCADE)
descricao = models.TextField(default='', blank=True, null=True)
slug = models.SlugField(unique=True)
image = models.ImageField(upload_to="products/%Y/%m/%d", blank=True, null=True)
def __str__(self):
return self.produto_nome
def get_absolute_url(self):
return reverse('produto:produto_detail', kwargs={'slug': self.slug})
class Ordem(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, blank=True, null=True)
data_pedido = models.DateTimeField(auto_now_add=True, null=True, blank=True)
enviado = models.BooleanField(default=False, null=True, blank=True)
transaction_id = models.CharField(max_length=200, null=True)
def __str__(self):
return str(self.id)
def get_total_preco(self):
total = 0
for pedido in self.produtos_itens.all():
total += pedido.get_total_item_preco()
return total
class OrdemItem(models.Model):
produto = models.ForeignKey(Produto, on_delete=models.SET_NULL, blank=True, null=True)
ordem = models.ForeignKey(Ordem, on_delete=models.SET_NULL, blank=True, null=True)
quantidade = models.IntegerField(default=0, null=True, blank=True)
data_add = models.DateTimeField(auto_now_add=True, null=True, blank=True)
def __str__(self):
return f'{self.quantidade} unidade de {self.produto.produto_nome}'
def get_total_item_preco(self):
return self.quantidade * self.produto.preco
I added a method in my models 'Ordem' to return the 'produto_nome'. And then I called in my admin
models.py
class Ordem(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, blank=True, null=True)
data_pedido = models.DateTimeField(auto_now_add=True, null=True, blank=True)
enviado = models.BooleanField(default=False, null=True, blank=True)
transaction_id = models.CharField(max_length=200, null=True)
def __str__(self):
return str(self.id)
def produtos(self):
return list(OrdemItem.objects.filter(ordem__id=self.id))
def get_total_preco(self):
total = 0
for pedido in self.produtos_itens.all():
total += pedido.get_total_item_preco()
return total
admin.py
class OrdemAdmin(admin.ModelAdmin):
list_display= ('id', 'enviado', 'produtos')
admin.site.register(Categoria)
admin.site.register(Produto, ProdutoAdmin)
admin.site.register(OrdemItem)
admin.site.register(Ordem, OrdemAdmin)

Django _set.all() filter in QuerySet

I have database and I want to extract specific data of specific user from queryset. Now i have this
VIEW
def index(request):
customerByName = Customer.objects.get(name='pablo')
shopListById = ShopList.objects.get(transaction_id=1)
shpoListSpecific = customerByName.shoplist_set.all()
specificProducts = shopListById.shoplistproduct_set.all()
context = {'customerByName':customerByName, 'shpoListSpecific':shpoListSpecific, 'shopListById':shopListById,
'specificProducts': specificProducts}
return render(request, 'QuickShopperApp/home.html', context)
MODELS
class Customer(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
device = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
if self.name:
name = self.name
else:
name = self.device
return str(name)
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
class ShopList(models.Model): # cart
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
#product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
def __str__(self):
return str(self.id)
class ShopListProduct(models.Model): # each ShopList will have multiple ShopListProduct
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
shopList = models.ForeignKey(ShopList, on_delete=models.SET_NULL, null=True) #shoplistitem.shoplist
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.product)
template.html
<h3>specificProducts: {{specificProducts}}</h3>
On my side i see items of specific customer.
specificProducts: <QuerySet [<ShopListProduct: Apple>, <ShopListProduct: Cucumber>, <ShopListProduct: Cucumber>]>
How can i get only Apple, Cucumber, Cucumber?
try this
'specificProducts': specificProducts.values_list('product__name')
or
'specificProducts': list(specificProducts.values_list('product__name', flat=True))
https://docs.djangoproject.com/en/3.1/ref/models/querysets/#values-list

Django: get the max count of a foreign key based on other foreign key

I have this Model:
class Complaint(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
name = models.CharField(max_length=255, unique=True)
definition = models.TextField(blank=False, default="")
is_violent = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name
class Meta:
ordering = ['name']
def get_absolute_url(self):
return reverse('complaint-details', kwargs={'pk': self.pk})
class Service(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
name = models.CharField(max_length=255, unique=True)
definition = models.TextField(blank=True, default="")
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('service-details', kwargs={'pk': self.pk})
class Location(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
location_name = models.CharField(max_length=255, unique=True)
loc_lat = models.DecimalField(max_digits=9, decimal_places=6)
loc_long = models.DecimalField(max_digits=9, decimal_places=6)
pop = models.PositiveIntegerField(default=500)
is_AOR = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.location_name
class Blotter(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True)#default=timezone.now().date()
date = models.DateField(blank=True)
time = models.TimeField(blank=True)
entry_number = models.CharField(max_length=255, unique=True,validators=[RegexValidator(r'^\d{1,255}$')])
complaints = models.ForeignKey(Complaint, on_delete=models.CASCADE, null=True, blank=True)
service = models.ForeignKey(Service, on_delete=models.CASCADE, null=True, blank=True)
information = models.TextField(blank=False, default="")
location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True, blank=True)
is_active = models.BooleanField(default=True)
class Meta:
ordering = ("date_created",)
def __str__(self):
return (self.entry_number)
def get_absolute_url(self):
return reverse('details-blotter', kwargs={'pk': self.pk})
And I have this serializer:
class APILocationListSerializer(serializers.Serializer):
address = serializers.CharField()
latitude = serializers.DecimalField(max_digits=9, decimal_places=5)
longitude = serializers.DecimalField(max_digits=9, decimal_places=5)
population= serializers.IntegerField()
crime_count=serializers.IntegerField()
crime_rate=serializers.DecimalField(max_digits=4, decimal_places=3)
is_aor = serializers.BooleanField()
class Meta:
model = Blotter
fields= [
'address',
'latitude',
'longitude',
'population',
'crime_count',
'crime_rate'
'is_aor',
]
def to_representation(self, value):
context = {
value['address']:
{
'coordinates':[value['latitude'],value['longitude']],
'Population': value['population'],
'Crime-Count': value['crime_count'],
'Crime-Rate': value['crime_rate'],
'Area-Of-Responsibility': value['is_aor'],
}
}
return context
And ListApiView:
class APILocationList(generics.ListAPIView):
serializer_class = APILocationListSerializer
def get_queryset(self):
q=Blotter.objects.values('location__location_name').annotate(
address=F('location__location_name'),
latitude=F('location__loc_lat'),
longitude=F('location__loc_long'),
population=F('location__pop'),
crime_count=Count('complaints', filter=Q(complaints__is_active=True) and Q(complaints__isnull=False)),
crime_rate=(Cast(F('crime_count'), FloatField())/Cast(F('population'), FloatField()))*100000,
is_aor=F('location__is_AOR')
)
q1 = q.filter(location__is_AOR=True).order_by('address')
query_search = self.request.GET.get("q")
if query_search:
q1 = q.filter(Q(location__is_AOR=True) and Q(location__location_name__icontains=query_search)).order_by('address')
return q1
I'm new to django and DRF. I want to achieve a result like this in my API Not Achieved
but this is the result that i've achieved so far Achieved
As you can see in the picture, I want to count the crime trend (highest count of a crime and the crime itself) in every location.
My questions are:
Is this even achievable/possible to get these results using just one query?
If yes, how?
If no, is there any other way to achieve these kind of results?
Thank you in advance!

Categories