If I have products that only can be sold is some regions. Also a customer can belong to several regions.
Example:
class Customer(models.Model):
firstname = models.CharField(max_length=100, default="")
class Product(models.Model):
productname = models.CharField(max_length=100, default="")
class Region(models.Model):
regionname = models.CharField(max_length=100, default="")
class CustomerRegionLink(models.Model):
customer = models.ForeignKey(Customer)
region = models.ForeignKey(Region)
class ProductRegionLink(models.Model):
product = models.ForeignKey(Product)
region = models.ForeignKey(Region)
If I now have a Customer object. How can I filter out which products can be ordered?
I have tried versions of:
thecustomer = Customer.objects.get(id=1)
prods = ProductRegionLink.object.filter(region__in=thecustomer.customerregionlink.all())
This errors like:
ValueError: Cannot use QuerySet for "CustomerRegionLink": Use a QuerySet for "Region".
Try
thecustomer = Customer.objects.get(id=1)
prods = ProductRegionLink.object.filter(region__in=[cr_link.region for cr_link in thecustomer.customerregionlink.all()])
As in your current query you are trying to find region in customerregionlink queryset not in region queryset or list.
Related
class Product(models.Model):
name = models.CharField(max_length=30)
class Order(models.Model):
order_number = models.CharField(max_length=30)
products = models.ManyToManyField(
Product,
through='OrderProduct',
related_name='orders'
)
class OrderProduct(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
price = models.CharField(max_length=30)
quantity = models.IntegerField(null = True)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
my data is already save in these Models now when i fetch order then i want to see Order product data also how can i see these data ?
again 1 order has multi order products
i try this
abc = Order.object.get(id = 1)
now how can i see the related products and its quantity and price?
Please try this.
abc = Order.object.get(id = 1)
OrdProducts = abc.product.all()
OrdProducts = abc.product.all()
for ord in OrdProducts:
print(ord.product)
print(ord.price)
print(ord.quantity)
I've got two models.
class Color(models.Model):
name = models.CharField(max_length=120, null=True, blank=True)
class Car(models.Model):
user = models.ForeignKey(Color, on_delete=models.CASCADE, default=None)
price = models.DecimalField(max_digits=10, decimal_places=2)
How can I get a queryset of Color instances where the Car instances that are related to those Color instances have a price > 1000?
Thanks!
You can use something like:
related_colors = Color.objects.filter(car_set__price__gt=1000)
Assuming you meant color instead of user? You can filter it as follows:
cars = models.Car.objects.filter(price__gte = 1000).values_list('color', flat = True)
I'm trying to query into three models. I need to get the amount products that are in the stores region location. These are my models:
class Store(models.Model):
name = models.CharField(max_length=255)
logo = models.URLField(null=True, blank=True)
user = models.OneToOneField(get_user_model(), models.CASCADE,
related_name="user_store")
region = models.CharField("Departamento", max_length=100)
city = models.CharField("Ciudad", max_length=100)
class Product(models.Model):
name = models.CharField("Nombre del Producto", max_length=255)
description = models.TextField()
stock = models.PositiveIntegerField()
seller = models.ForeignKey(User, on_delete=models.CASCADE)
Product is related with user and it is related to store, what I want to do is something like this:
{
"Risaralda": 1523,
"Cundinamarca": 8541
}
where keys "Risaralda" and "Cundinamarca" are regions and values are the product amount in these places
I tried something like this
products = Product.objects.filter(
seller__user_store__region__in=Store.objects.filter()
.values("region").distinct())
And I got products in stores regions but i need to count how many products are in every store regions
thank you a lot
Something like this should do the trick:
from django.db.models import F
from django.db.models import Count
Product.objects.annotate(region=F('seller__user_store__region')).annotate(num_products=Count('id')).values_list('region', 'num_products')
models.py
class Customer(models.Model):
customer_name = models.CharField(max_length=50)
address = models.CharField(max_length=100)
bill_no = models.CharField(max_length=8)
class Sell(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
total = models.IntegerField()
vat = models.IntegerField()
How do get the customer id from Sell model/object?
like Sell.objects.get(pk=..)
You can get using foreign key concept.
Here you can get the pk of Customer model using customer field of Sell model, it will be customer__pk.
Similarly customer_name you can get by customer__customer_name and address using customer__address and bill_no using customer__bill_no.
Note: Remember it is fieldnameincurrentmodel__othermodelfieldname, it is the double underscore.
Sell.objects.get(pk=customer__pk)
I have 2 tables:
Product(id, name)
Attribute(id, product_id, name, value)
How can I join the table "Attribute" 2 times when searching products? They must be in one query because of paging later.
An example: Search products which must have 2 attributes - one for name=att1, value=value1 and another for name=att2, value=value2.
Source Code:
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100, null=False)
class Attribute(models.Model):
attribute_id = models.AutoField(primary_key=True)
product = models.ForeignKey(Product, null=False)
name = models.CharField(max_length=100, null=False)
value = models.CharField(max_length=100, null=False)
A query that not working:
Product.objects.select_related().filter('attribute__name': 'n1', 'attribute__value':'v1').filter('attribute__name': 'n2', 'attribute__value':'v2')
You don't need to join them 2 times. You can create a model with ForignKey then get the set of relate attribute
For example :
you create model like this
class Product(models.Model):
name = models.CharField(max_length=100)
class Attribute(models.Model):
product = models.ForeignKey(Product)
name = models.CharField(max_length=100)
value = models.IntegerField()
You can get product item by call
item = Product.objects.get(id=xxx)
Then get all list of attribute relate to this item
from django.db.models import Q
attr = item.attribute_set.filter(Q(name='name1') | Q(name='name2'))
Use something like this:
p = Product.objects.get(pk=1)
filtered = p.attribute_set.filter(name__in=['n1','n2'],value__in=['v1','v2'])