please can anyone help me out am stuck i want to access items in the item model which i have referenced in the OrderItem model but am trying to access the item from Order model
here are the models
here is the model that am using to access
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
ref_code = models.CharField(max_length=20)
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
order_date = models.DateTimeField()
ordered = models.BooleanField(default=False)
shipping_address = models.ForeignKey('Address',on_delete=models.SET_NULL,related_name='shipping_address',blank=True,null=True)
payment = models.ForeignKey('Payment',on_delete=models.SET_NULL,blank=True,null=True)
being_delivered = models.BooleanField(default=False)
received = models.BooleanField(default=False)
refund_requested = models.BooleanField(default=False)
refund_granted = models.BooleanField(default=False)
Here is the parent model which i want to access
class OrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
ordered_order = models.BooleanField(default=False)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
and the item am trying to access must in this model
class Item(models.Model):
title = models.CharField(max_length=100)
price = models.IntegerField()
discount_price = models.IntegerField(blank=True, null=True)
category = models.ForeignKey(Categories, on_delete=models.DO_NOTHING)
tags = models.ManyToManyField(Tags, related_name='itemTags')
slug = models.SlugField(max_length=200, unique=True)
size = models.CharField(blank=True, null=True, max_length=5)
model = models.CharField(max_length=100, blank=True, null=True)
description = models.TextField()
quantity = models.IntegerField(default=1)
image = models.ImageField()
color = models.CharField(max_length=100, blank=True, null=True)
brand = models.CharField(max_length=100, blank=True, null=True)
Display = models.DecimalField(max_digits=100,
decimal_places=1,
blank=True,
null=True)
ram = models.CharField(max_length=100, blank=True, null=True)
material = models.CharField(max_length=100, blank=True, null=True)
hdd = models.CharField(max_length=100, blank=True, null=True)
size = models.CharField(max_length=100, blank=True, null=True)
lens = models.CharField(max_length=100, blank=True, null=True)
created_at = models.DateField(auto_now_add=True)
i was trying with this but seem not to work
recent_orders=Order.objects.filter(user=2)
for item in recent_orders:
print(item.items.item.title)
can anyone help me out Please!!!
You need thi code:
recent_orders=Order.objects.filter(user=2)
for order in recent_orders:
for order_item in order.items:
print(order_item.item.title)
try to give different names to all your variables, this will make programming more effective
Related
I want to assign some location to an item and also save it to other app. So, when I make changes to it from one app, the other gets updated too.
location.py:
class ManageLocation(models.Model):
product = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField()
warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE)
zone = models.ForeignKey(Zone, on_delete=models.CASCADE, default='1')
section = models.ForeignKey(Section, on_delete=models.CASCADE, default='1')
level = models.ForeignKey(Level, on_delete=models.CASCADE, default='1')
where the referenced keys are seperate classes with name and description.
***mainpurchases:***
class MainPurchases(models.Model):
METHOD_A = 'CASH'
METHOD_B = 'CREDIT'
PAYMENT_METHODS = [
(METHOD_A, 'CASH'),
(METHOD_B, 'CREDIT'),
]
product = models.ForeignKey(Item, on_delete=models.PROTECT)
#assign-warehouse
#assign-level
#assign-zone
#assign-section
quantity = models.PositiveSmallIntegerField()
purchase_price = models.DecimalField(max_digits=6, decimal_places=2)
paid_amount = models.DecimalField(max_digits=6, decimal_places=2)
date_created = models.DateTimeField(auto_now_add=True)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
outlet = models.ForeignKey(Outlet, on_delete=models.CASCADE, blank=True, null=True)
payment_method = models.CharField(max_length=6, choices=PAYMENT_METHODS, default=METHOD_A)
This is where I want to assign it and save it in managelocations.
better approaches are appreciated.
I can't find the answer to the following question about learning application building:
I have task model, which has one-to-many relations with other models: text_message, image_message, video_message, quiz_message, web_page_message (let's call them blocks) and I want to allow the user to choose the order in which these blocks will be sent.
The issue is that if I just add small integer field called 'order' in these blocks' classes - user still can choose a number that would be much bigger than the overall number of existing blocks.
So what is the best way to make such ordering?
Thank you for your answers.
UPD.:
Sorry if the code is not perfect, it is my first real Django project.
Added my models.
Questions:
How to make an order through all these messages?
How to design models in such a way to give the ability to the user to change this ordering?
class task(models.Model):
employees_appointed_id = models.ManyToManyField(profile, related_name='task_to_appointed_users')
employees_finished_id = models.ManyToManyField(profile, related_name='task_to_users_finished', blank=True, null=True)
creator_user_id = models.ForeignKey('profile', on_delete=models.CASCADE, related_name='who_created_task')
description = models.TextField(max_length=1000)
created_datetime = models.DateTimeField(models.DateTimeField(auto_now=True))
deadline = models.DateTimeField(blank=True, null=True)
title = models.CharField(max_length=55)
course = models.ForeignKey('course', on_delete=models.CASCADE)
mentor = models.ManyToManyField(profile, blank=True, null=True, related_name='task_to_profile')
class text_message(models.Model):
text = models.CharField(max_length=3900)
number_by_order = models.IntegerField()
task = models.ForeignKey('task', on_delete=models.CASCADE, related_name='message_to_task')
creator_user_id = models.ForeignKey('profile', on_delete=models.CASCADE, related_name='message_to_creator_user')
course_id = models.ForeignKey('course', on_delete=models.CASCADE, related_name='messages_to_course')
created_datetime = models.DateTimeField(auto_now=True)
class video_message(models.Model):
description = models.CharField(max_length=1024)
media = models.ForeignKey('media', on_delete=models.CASCADE)
task = models.ForeignKey('task', on_delete=models.CASCADE, related_name='video_message_to_task')
class web_page_message(models.Model):
link = models.CharField(max_length=255)
description = models.TextField(max_length=2000, blank=True, null=True)
task = models.ForeignKey('task', on_delete=models.CASCADE, related_name='web_page_to_task')
class image_message(models.Model):
media = models.ForeignKey('media', on_delete=models.CASCADE)
description = models.TextField(max_length=1024)
task = models.ForeignKey('task', on_delete=models.CASCADE, related_name='image_message_to_task')
class quiz_message(models.Model):
question = models.CharField(max_length=300)
option_1 = models.CharField(max_length=100)
option_2 = models.CharField(max_length=100)
option_3 = models.CharField(max_length=100, blank=True, null=True)
option_4 = models.CharField(max_length=100, blank=True, null=True)
option_5 = models.CharField(max_length=100, blank=True, null=True)
option_6 = models.CharField(max_length=100, blank=True, null=True)
option_7 = models.CharField(max_length=100, blank=True, null=True)
option_8 = models.CharField(max_length=100, blank=True, null=True)
option_9 = models.CharField(max_length=100, blank=True, null=True)
option_10 = models.CharField(max_length=100, blank=True, null=True)
explanation = models.CharField(max_length=200, blank=True, null=True)
task = models.ForeignKey('task', on_delete=models.CASCADE, related_name='quiz_message_to_task')
I'm working on a Django Ecommerce project where product has several attributes like. size, color( A single product can have multiple attributes with different size and color). No i'm trying to filter products using django_filters but unable to filter by its attributes.
Product Model:
class Product(models.Model):
variations = (
('None', 'None'),
('Size', 'Size'),
)
name = models.CharField(max_length=200, unique=True)
store = models.ManyToManyField(Store)
slug = models.SlugField(null=True, blank=True, unique=True, max_length=500)
sku = models.CharField(max_length=30, null=True)
tax = models.IntegerField(null=True, blank=True)
stock = models.CharField(max_length=10, null=True)
variations = models.CharField(choices=variations, max_length=20)
short_description = models.CharField(max_length=500, null=True)
details = RichTextUploadingField(null=True, blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
discounted_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
image = models.ImageField(upload_to='product/images', default='product.png', null=True,
blank=True)
image_one = models.ImageField(upload_to='product/images', null=True, blank=True)
image_two = models.ImageField(upload_to='product/images', null=True, blank=True)
image_three = models.ImageField(upload_to='product/images', null=True, blank=True)
image_four = models.ImageField(upload_to='product/images', null=True, blank=True)
image_five = models.ImageField(upload_to='product/images', null=True, blank=True)
tags = models.ManyToManyField(Tags)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True,
related_name='products')
status = models.CharField(max_length=20, choices=(('Active', 'Active'), ('Inactive',
'Inactive')))
brand = models.ForeignKey(Brand, on_delete=models.PROTECT, blank=True, null=True)
offer = models.ForeignKey(Offer, on_delete=models.CASCADE, null=True,
blank=True) # This is used only for filtration
Product attribute model
class ProductAttribute(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
size = models.ForeignKey(Size, on_delete=models.CASCADE, null=True, blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2, validators=
[MinValueValidator(1)])
discounted_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
stock = models.CharField(max_length=10, null=True)
The standard approach would be to define the attributes in the "Product" model. However, if you insist on doing this, the code will be:
filtered_ProductAttributes=ProductAttribute.objects.filter(size="12")
products=[filtered_ProductAttribute.product for filtered_ProductAttribute in filtered_ProductAttributes]
As you can see the code seems very inefficient, therefore, as was suggested in the beginning put the attributes in the "Product" model and you will have:
products=Product.objects.filter(size="12")
Refining your model will help you to filter.
With my experience following model approach will be more suitable:
class Attributes(models.Model):
name = models.CharField(max_length=50, default=None)
slug = models.SlugField(max_length=200, unique=True,null=True)
class AttributeTerms(models.Model):
name = models.CharField(max_length=50, blank =True)
attribute = models.ForeignKey(Attributes, on_delete=models.CASCADE)
class Products(models.Model):
name = models.CharField(max_length=250,null=True, blank=True,)
slug = models.SlugField(max_length=200, unique=True,null=True)
class ProductAttribute(models.Model):
product = models.ForeignKey(Products,on_delete=models.CASCADE, related_name='attributes', default=None)
attributes = models.ForeignKey(Attributes,on_delete=models.CASCADE, related_name='attributes', default=None)
values = models.ForeignKey(AttributeTerms, on_delete=models.CASCADE, related_name='attributes', default=None)
class ProductVariant(models.Model):
product = models.ForeignKey(Products,on_delete=models.CASCADE)
variant = models.ForeignKey(ProductAttribute,on_delete=models.CASCADE, null = True, default=None)
stock = models.IntegerField(default=None)
stock_threshold = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
sku = models.CharField(max_length= 250, default=None)
sale_price = models.DecimalField(max_digits=10, decimal_places=2)
I have a product model. I need to autocomplete product name into input field. How can I code?
class Product(models.Model):
product_name = models.CharField(max_length=255)
product_detail = models.TextField(blank=True, null=True)
product_price = models.FloatField(blank=True)
category = models.CharField(max_length=30)
product_image = models.ImageField(upload_to='pictures/%Y/%m/%d/', max_length=255, blank=True, null=True)
product_amount = models.IntegerField(blank=True, null=True)
del_flag = models.BooleanField(default=False)
def __str__(self):
return self.product_name
Cant actually find anything like what i am trying to do with wanting to use case statements and left joins using DRF Django Rest Framework, yes this could be done on the front end of the project i am working on but id rather not have to let the front end potentially sending 100s of requests when loading a product list for example.
Nothing i can really add to this but i have tried many different ways of doing the below
SELECT
p.itemno,
CASE
WHEN cp.price IS NULL THEN p.HighSell
ELSE cp.price
END AS price
FROM
api_product AS p
LEFT JOIN
api_customerprices AS cp ON p.itemno = cp.itemno
AND cp.customerno = 'Examplecust'
WHERE
p.FreeStock > 0
or restockDate > '1900-01-01'
Here Are my models:
class Product(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
itemno = models.CharField(max_length=100)
description = models.TextField(null=True)
colour = models.CharField(max_length=100, null=True)
manufacturerCode = models.CharField(max_length = 100, null=True)
RRP = models.DecimalField(max_digits=6, decimal_places=2, null=True)
SSP = models.DecimalField(max_digits=6, decimal_places=2,null=True)
FreeStock = models.IntegerField(null=True)
ItemSpec1 = models.CharField(max_length=100, null=True)
ItemSpec2 = models.CharField(max_length=100, null=True)
ItemSpec3 = models.CharField(max_length=100, null=True)
ItemSpec4 = models.CharField(max_length=100, null=True)
ItemSpec5 = models.CharField(max_length=100, null=True)
ItemSpec6 = models.CharField(max_length=100, null=True)
ItemSpec7 = models.CharField(max_length=100, null=True)
ItemSpec8 = models.CharField(max_length=100, null=True)
ItemSpec9 = models.CharField(max_length=100, null=True)
ItemSpec10 = models.CharField(max_length=100, null=True)
TI = models.IntegerField(null=True)
HI = models.IntegerField(null=True)
Item_Height = models.DecimalField(max_digits=6, decimal_places=2, null=True)
Item_Length = models.DecimalField(max_digits=6, decimal_places=2, null=True)
Item_Width = models.DecimalField(max_digits=6, decimal_places=2, null=True)
ProductPaging_Height = models.DecimalField(max_digits=6, decimal_places=2, null=True)
ProductPaging_Length = models.DecimalField(max_digits=6, decimal_places=2, null=True)
ProductPaging_Width = models.DecimalField(max_digits=6, decimal_places=2, null=True)
CartonHeight = models.DecimalField(max_digits=6, decimal_places=2, null=True)
CartonLength = models.DecimalField(max_digits=6, decimal_places=2, null=True)
CartonWidth = models.DecimalField(max_digits=6, decimal_places=2, null=True)
palletQty = models.IntegerField(null=True)
cartonQty = models.IntegerField(null=True)
restockDate = models.DateField(null=True)
IPG = models.CharField(max_length=100, null=True)
CatalogueTheme = models.CharField(max_length=100, null=True)
Analysis2 = models.CharField(max_length=100, null=True)
Electrical_or_Housewares = models.CharField(max_length=100, null=True)
HighSell = models.DecimalField(max_digits=6, decimal_places=2, null=True)
Analysis1 = models.CharField(max_length=100, null=True)
Image = models.TextField(null=True, blank=True)
MarketingText = models.TextField(null=True, blank=True)
SearchTerms = models.TextField(null=True, blank=True)
ItemVariant = models.CharField(max_length=100)
Categories = models.CharField(max_length=249, null=True)
def __str__(self):
return self.itemno
class CustomerPrices(models.Model):
customerNo = models.CharField(max_length=20)
itemno = models.CharField(max_length=20)
price = models.DecimalField(max_digits=6, decimal_places=2)
startDate = models.DateField()
endDate = models.DateField()
def __str__(self):
return self.customerNo
Here are my Serializers
class OauthProdListSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = (
'id',
'itemno',
'description',
'colour',
'RRP',
'SSP',
'manufacturerCode',
'FreeStock',
'restockDate',
'Image',
'HighSell',
'ItemVariant',
'Categories'
)
class OCustomerPricesSerializer(serializers.ModelSerializer):
class Meta:
model = CustomerPrices
fields = (
'id',
'customerNo',
'itemno',
'price'
)
Found a way of performing what i wanted, turned out i was missing knowledge on the SerializerMethodField() method, once i found out that i got it pretty quickly.
class ProdListSerializer(ModelSerializer):
price = SerializerMethodField()
class Meta:
model = Product
fields = [
'id',
'itemno',
'description',
'colour',
'RRP',
'SSP',
'manufacturerCode',
'FreeStock',
'restockDate',
'Image',
'ItemVariant',
'Categories',
'price'
]
def get_price(self, obj):
itemno = obj.itemno
customerNo = self._context['view'].request.query_params.get('customerNo', '')
if customerNo:
customerPrice = CustomerPrices.objects.filter(
Q(customerNo=customerNo) &
Q(itemno=itemno)
).values('price').first()
if customerPrice:
return customerPrice
else:
return Product.objects.filter(itemno=itemno).values('HighSell').first()
else:
return Product.objects.filter(itemno=itemno).values('HighSell').first()
I am just writing this off the top of my head so it will take some effort on your part to get it working.
You do not have a relationship between your Product and CustomerPrices. You will either need to add a Foreignkey between the two tables directly or, you will need to add an intermediate table with foreignkeys between them.
Your query will be something like:
Q is a django query object - see Complex lookups with Q objects
results = CustomerPrices.objects.filter(
Q(itemno__FreeStock__gt=0) | Q(itemno__restockDate__gt='1900-0-01'),
customerno='Examplecust'
)
# Your case statement can be handled in your code logic:
def case_statement(result):
if not result.price:
return result.HighSell
return result.price
I am not exactly sure what you mean, but you can get the SQL for all the tables in an app by running this command:
python manage.py sqlall your_app
or you want to convert sql to django use :
Person.objects.raw('your_sql_query')