Django Query: join a table 2 times - django

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'])

Related

Problem with response values with join in django query?

i have this models.
class Product(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=50)
PublicationDate = models.DateField()
trend = models.IntegerField()
class User_list(models.Model):
product_id = ForeignKey(Product, on_delete=models.CASCADE)
userid = models.IntegerField()
i make a join query with select related
data = User_list.objects.select_related('product_id')
but the response don't get me Product fields value.
it's get me only User_list values, like this
"[{\"model\": \"app.user_list\", \"pk\": 1, \"fields\": {\"product_id\": 11916, \"userid\": 9}}]"
What's the problem?

how can i get data manytomay relation from 3 tables django

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)

Django filter many to many

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.

django - Filter foreign key in a queryset

In the following model:
class Product(models.Model):
name = models.CharField(max_length = 255)
created_in = models.DateTimeField(auto_now=True)
class Price(models.Model):
product = models.ForeignKey(Product)
price = models.DecimalField(max_digits=6, decimal_places=2)
created_in = models.DateTimeField(auto_now=True)
I want to do things like this:
products = Product.objects.filter(price__gte=Decimal(10)) #It considered all prices I just need the last one
How do i query a product considering only the last price "created_in" related?
Thanks!!
latest() is what you need:
Returns the latest object in the table, by date, using the field_name
provided as the date field.
products = Product.objects.filter(price__gte=Decimal(10)).latest('price__created_in')

django, many to many relation get_field name

I had two django models connected with many to many relationship.
First model:
class Category(models.Model):
name = models.CharField(max_length=255)
products = models.ManyToManyField(Product, related_name='categories',
blank=True, null=True,
verbose_name=_('Products'),
)
second model:
class Product(models.Model):
description = models.TextField(verbose_name=_('Description'), default='')
manifactor = models.CharField(verbose_name=_('Manifactor'), default='Blackberry', max_length=255)
ok, so:
product = Product.objects.all()[0]
product.categories - give me a list of categories for this product.
but:
product._meta.many_to_many - return empty list [].
and product._meta.get_field('categories') - return None.
Why ?
How can I get the verbose name of category field from product object ?
You can add
categories = models.ManyToManyField(Category,
through=Category.products.through)
to your Product model