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)
Related
I have a model Allotment
class Kit(models.Model):
kit_types = (('FLC', 'FLC'), ('FSC', 'FSC'), ('Crate', 'Crate'), ('PP Box', 'PP Box'))
kit_name = models.CharField(max_length=500, default=0)
kit_type = models.CharField(max_length=50, default=0, choices=kit_types, blank=True, null=True)
class AllotmentFlow(models.Model):
flow = models.ForeignKey(Flow, on_delete=models.CASCADE)
kit = models.ForeignKey(Kit, on_delete=models.CASCADE)
asked_quantity = models.IntegerField(default=0)
alloted_quantity = models.IntegerField(default=0)
class Allotment(models.Model):
transaction_no = models.IntegerField(default=0)
dispatch_date = models.DateTimeField(default=datetime.now)
send_from_warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE)
flows = models.ManyToManyField(AllotmentFlow)
For a stacked graph I am trying to get the data of different kit_type alloted in different months.
For that I have tried annotate but it isn't getting the desired results
dataset = Allotment.objects.all().annotate(
month=TruncMonth('dispatch_date')).values(
'month').annotate(dcount=Count('flows__kit__kit_type')).values('month', 'dcount')
Expected Output:
[{'month':xyz, 'kit_type':foo, count:123},...]
I am getting the month and count of kit type from above but how do I segregate it by kit_type?
having a field that represents your choice field names in this query is difficult
instead how about use the Count filter argument and annotate to get what you want
dataset = Allotment.objects.all().annotate(month=TruncMonth('dispatch_date')).values('month').annotate(
FLC_count=Count('flows__kit__kit_type', filter=Q(flows__kit__kit_type="FLC")),
FSC_count=Count('flows__kit__kit_type', filter=Q(flows__kit__kit_type="FSC")),
Crate_count=Count('flows__kit__kit_type', filter=Q(flows__kit__kit_type="Crate")),
PP_Box_count=Count('flows__kit__kit_type', filter=Q(flows__kit__kit_type="PP_Box")),
).values('month', 'FLC_count', 'FSC_count', 'Crate_count', 'PP_Box_count')
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.
In my app i need to store invoices (Invoice) of known products (Product) to calculate points for each seller (User). I'm trying to create form to insert basic invoice data plus inline form with sold products info. To handle it i create model like this:
class Product(models.Model):
group = models.CharField(max_length = 200, blank = False)
mark = models.CharField(max_length = 200, blank = True)
points = models.IntegerField(blank = False)
class Invoice(models.Model):
price = models.FloatField(blank=False)
file = models.FileField(blank=False)
product = models.ManyToManyField(Product, through='Sold')
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField()
date_created = models.DateField(auto_now_add=True)
date_updated = models.DateField(auto_now=True)
class Sold(models.Model):
invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(default=1)
I tried to manage it via django-admin and it work fine with admin.py:
class ProductTabular(admin.TabularInline):
model = Invoice.product.through
class InvoiceAdmin(admin.ModelAdmin):
inlines = [ProductTabular]
exclude = ('product', )
class Meta:
model = Invoice
admin.site.register(Invoice, InvoiceAdmin)
but i'm unable to create such form in own templates. Please, can you help me with views.py and template to get same result as for the django-admin?
I tried via invoce form with inlineformset_factory for the Sold model, but i can't figure out how to save it. Thanks for any help!
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'])
Guys,
Is there an easy way to return different fields names from different models by chaining joins?
My model:
Class Item(models.Model):
item_code = models.CharField(max_length=10)
name = models.CharField(max_length=255)
...
Class Stock(models.Model):
item_code = models.ForeignKey( Item )
userid = models.ForeignKey( User )
qty = models.IntegerField()
...
I want to select " Item.Item_code, Item.name, Stock.qty where Stock.userid=2 and Item.item_code = Stock.Item_Code"
How do i do this in Django?
Gath
I want to select " Item.Item_code, Item.name, Stock.qty where Stock.userid=2 and Item.item_code = Stock.Item_Code"
You can pick these specific fields only using one SQL, provided you start from the Stock model. For instance
q = Stock.objects.select_related('userid', 'item_code').filter(
userid__id = 2).values('item_code__item_code', 'item_code__name', 'qty')
This will help if you want to limit the data and then number of queries. If you are not concerned with this then do:
q = Stock.objects.filter(userid__id = 2)
for stock in q:
print stock.item_code.item_code
print stock.item_code.name
print stock.qty
This will return a queryset with only those fields you have chose using values. You can then iterate through it.
PS: Re: your models.
Class Stock(models.Model):
item_code = models.ForeignKey( Item )
userid = models.ForeignKey( User )
qty = models.IntegerField()
...
It is a good idea to use the model name in lower case for FK relationships. For e.g. you ought to write:
Class Stock(models.Model):
item = models.ForeignKey( Item ) # Changed
user = models.ForeignKey( User ) # Changed
qty = models.IntegerField()
...
You can also use this:
Stock.objects.filter(user=2).values('item__item_code', 'item__name')
First of all change fileds names
Read this very carefuly http://docs.djangoproject.com/en/dev/ref/models/querysets/
Class Item(models.Model):
item_code = models.CharField(max_length=10)
name = models.CharField(max_length=255)
...
Class Stock(models.Model):
item = models.ForeignKey( Item )
user = models.ForeignKey( User )
qty = models.IntegerField()
...
#view
stocks = Stock.objects.filter(user=2)
for stock in stocks:
print stock.item.item_code, stock.item.name
#one query version