Get data from Inherit Model Django - python

Im working in my Python Django ecommerce project.Now i have 2 classes Item and BookItem :
class Item(models.Model):
item_name = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200,unique=True)
description = models.TextField(max_length=500, blank=True)
price = models.IntegerField()
images = models.ImageField(upload_to='photos/products')
stock = models.IntegerField()
is_available = models.BooleanField(default = True)
category = models.ForeignKey(Category,on_delete = models.CASCADE)
created_date = models.DateTimeField(auto_now=True)
modified_date= models.DateTimeField(auto_now=True)
def __str__(self):
return self.item_name
def get_url(self):
return reverse('item_detail',args=[self.category.slug, self.slug])
class BookItem(Item):
book = models.ForeignKey(Book,on_delete = models.CASCADE)
I want to get BookItem data from the class Item.Anyone knows how to do it ?

Get Book data for all Items
Item.objects.all().values(
"book__book_name",
"book__import_price",
# "class_name__field_name", structure of the query
)
To filter Item data using Book fields
[filter Items where book name is 'bookname']
Item.objects.filter(book__book_name="bookname")

Related

How can I solve this python problem?[django]

Why cannot I migrate. It says assertion error. Here is the pic
# Create your models here.
class Product(models.Model):
product_id= models.AutoField()
product_name = models.CharField(max_length=50)
category = models.CharField(max_length=50, default="" )
subcategory = models.CharField(max_length=50, default="" )
price = models.IntegerField(default=0)
desc = models.CharField(max_length=300)
pub_date = models.DateField()
image = models.ImageField(upload_to='shop/images', default="")
def __str__(self):
return self.product_name
It conflicted product_id field within Product Table. Or if you want to create product_id as your primary key in your product table just write models.AutoField(primary_key=True)

Is there any option to filter data by model's filed in django python?

I am new to Django, Is there any option to display data by choice? I am able to filter by category but I have to filter by choices or model's field. Or is there any option to multiple filters in one template? Or can we filter by using two foreign keys in one model? Here is my Product model where I have used filed (member) for the filter but I could not do that then I have used another model for the filter.
class Product(models.Model):
MEMBER = (
('For Kids', 'For Kids'),
('For Lover', 'For Lover',),
('For Teacher', 'For Teacher'),
('For Boss', 'For Boss'),
)
category = models.ForeignKey(Category, related_name='products', on_delete=models.PROTECT)
member = models.CharField(max_length=200,choices = MEMBER)
title = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%d/%m/%Y', blank =True)
description = models.TextField(blank=True)
price = models.IntegerField(default=0)
stock = models.PositiveIntegerField()
available = models.BooleanField(True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-title',)
index_together = (('id','slug'),)
def __str__(self):
return self.title
and my category model :
class Category(models.Model):
title = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
image = models.ImageField(upload_to='products/%d/%m/%Y', blank =True)
parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.PROTECT)
class Meta:
unique_together = ('slug', 'parent',)
ordering = ('title',)
verbose_name = 'category'
verbose_name_plural = 'categories'
view.py
def eventmore(request,id,slug):
products = None
categories = Category.get_all_categories()
categoryID = request.GET.get('category')
if categoryID:
products = Product.get_all_products_by_categoryid(categoryID)
else:
products = Product.get_all_products()
data = {}
data['products'] = products
data['categories'] = categories
return render(request, 'events-more.html', data)
What can I do to filter by choices(member) or How can I make a nested category or filter data by nested?
Here you can find all the info you need https://docs.djangoproject.com/en/3.1/topics/db/queries/ and yes you can filter multiple times and/or with multiple arguments.
For example:
data_entries = Data.objects.filter(name='max', age=10).filter(email='max#gmail.com')
or
data_entries = Data.objcets.filter(name='max')
data_entires = data_entries.filter(age=10, email='max#gmail.com')
will produce the same result.
In your case just filter it with regular text value:
category = Category.objcets.get(pk=pk)
product = Product.objects.filter(member='For Kids', category=category)

Shopping cart DB not showing number of Individual Items Ordered

I'm trying to create a shopping cart model, I've created the Order Model, OrderItem model and Also the Item model. Although I find it difficult to link the order it model to the order in the API view.
here's the Model
class Pizza(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60)
desc = models.CharField(max_length=150)
price = models.IntegerField()
url = models.CharField(max_length=250)
def __str__(self):
return self.name
class OrderItem(models.Model):
id = models.AutoField(primary_key=True)
product = models.ForeignKey("Pizza", on_delete=models.CASCADE, null=True)
date_added = models.DateTimeField(auto_now=True)
date_ordered = models.DateTimeField(null=True)
amount = models.IntegerField(null=True)
def __str__(self):
return self.product.name
class Order(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60)
email = models.CharField(max_length=150)
address = models.CharField(max_length=150)
total = models.IntegerField()
created_at = models.DateTimeField(default=timezone.now)
items = models.ManyToManyField(OrderItem)
def __str__(self):
return self.name
//The viewset
class OrderViewSet(viewsets.HyperlinkedModelSerializer):
# permission_classes = [IsPostOrIsAuthenticated,]
serializer_class = OrderSerializer
queryset = Order.objects.all().order_by('-created_at')
Currently, I cant display the amount attribute of the order item in my API, It just shows the id and Also the link to the individual orderitem in an order
I think for cart you can use external fields on relations between Order and Pizza. Documentation about this here
Your models looks like:
class Pizza(models.Model):
name = models.CharField(max_length=60)
desc = models.CharField(max_length=150)
price = models.IntegerField()
url = models.CharField(max_length=250)
def __str__(self):
return self.name
class Order(models.Model):
name = models.CharField(max_length=60)
email = models.CharField(max_length=150)
address = models.CharField(max_length=150)
total = models.IntegerField()
created_at = models.DateTimeField(auto_now=True)
items = models.ManyToManyField(Pizza, through='OrderItem')
def __str__(self):
return self.name
class OrderItem(models.Model):
product = models.ForeignKey('Pizza', on_delete=models.CASCADE, null=True)
order = models.ForeignKey('Order', on_delete=models.CASCADE, null=True)
date_added = models.DateTimeField(auto_now=True)
date_ordered = models.DateTimeField(null=True)
amount = models.IntegerField(null=True)
def __str__(self):
return self.product.name
Example, how you can get dict of items amount in order:
order = Order.objects.filter('-created_at').first() // get last order
cart = {item.pk: item.amount for item in order.items}

django adding products to a list via m2m relationship

How do I add products into a preexisting list? Any guidance would be most appreciated.
I get the following error:
ValueError at /core_lists/test_list/
Cannot assign "": "ListHasProducts.product" must be a "Product" instance.
models.py
class Product(models.Model):
brand = models.CharField(max_length=100)
title = models.CharField(max_length=100)
url = models.URLField()
price = models.DecimalField(max_digits=8, decimal_places=2)
created_at = models.DateTimeField('date published', auto_now_add = True)
updated_at = models.DateTimeField('date updated', auto_now = True)
def __str__(self):
return self.title
class List(models.Model):
name = models.CharField(max_length=50)
description = models.CharField(max_length=100)
category = models.CharField(max_length=50)
created_at = models.DateTimeField('date published', auto_now_add = True)
updated_at = models.DateTimeField('date updated', auto_now = True)
products = models.ManyToManyField(Product, through='ListHasProducts')
def __str__(self):
return self.name
class ListHasProducts(models.Model):
list = models.ForeignKey(List, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
views.py
def testList(request):
test_form = ProductsForm
if request.method == 'POST':
test_form = ProductsForm(request.POST)
if test_form.is_valid():
test_form.save()
ListHasProducts(list=List.objects.get(pk=13), product=test_form)
ListHasProducts.save()
return HttpResponseRedirect(reverse('core_lists:test_list'))
according to django document
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-models
you shoud have related_name
class List(models.Model):
name = models.CharField(max_length=50)
description = models.CharField(max_length=100)
category = models.CharField(max_length=50)
products = models.ManyToManyField(Product, related_name='lists')

Save a many to many object inside a django model?

I am still learning to use Django and so I am a bit unclear on something.
I have a product model and category model. A product can lie in multiple categories and multiple categories can have the same product.
So, its a many to many relationship. Now, I want to allow the user to select multiple categories from the html and then I want to save the categories and link them to the category object in my product model. I am completely lost about it.
One way would be to use Modelform but I dont want to go that way. Is there any other way I can accomplish this?
models.py:
class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True,
help_text='Unique value for product page URL, created from name.')
description = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords", max_length=255,
help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField("Meta Description", max_length=255,
help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('catalog:categories', kwargs={'category_slug': self.slug})
class Meta:
ordering = ['-created_at']
verbose_name_plural = 'Categories'
class Product(models.Model):
name = models.CharField(max_length=255, unique=True)
slug = models.SlugField(max_length=255, unique=True,
help_text='Unique value for product page URL, created from name.')
brand = models.CharField(max_length=50)
sku = models.CharField(max_length=50)
price = models.DecimalField(max_digits=9, decimal_places=2)
old_price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, default=0.00)
thumbnail = models.FileField(upload_to='static/images/products/thumbnails')
imageurls = models.CharField(max_length=1000)
is_active = models.BooleanField(default=True)
is_bestseller = models.BooleanField(default=False)
is_featured = models.BooleanField(default=False)
quantity = models.IntegerField()
description = models.TextField()
meta_keywords = models.CharField(max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField(max_length=255, help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
categories = models.ManyToManyField(Category)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('catalog:products', kwargs={'product_slug': self.slug})
def sale_price(self):
if self.old_price > self.price:
return self.price
else:
return None
class Meta:
ordering = ['-created_at']
part of views.py:
if request.method =='POST':
print ('entered')
name = request.POST['name']
brand = request.POST['brand']
sku = request.POST['sku']
price = request.POST['price']
quantity = request.POST['quantity']
description = request.POST['description']
imageurls = request.POST['urls']
print('imageurls',imageurls)
categorylist = request.POST['categories']
print('categorylist',categorylist)
categories = re.findall(r"[\w']+", categorylist)
print categories
imageurls = imageurls.split('~')
print('iageurls',imageurls)
for x in categories:
categoryobj = Category.objects.filter(name=x).values()
print ('categoryobj',categoryobj)
# Product.objects.create(name=name,sku=sku,brand=brand,price=price,quantity=quantity,description=description,imageurls=imageurls,categories=categoryobj)
return HttpResponse('success')
Try to save the above way gives me error.
product=Product.objects.create(name=name,sku=sku,brand=brand,price=price,quantity=quantity,description=description,imageurls=imageurls)
category_queryset = []
for x in categories:
category = Category.objects.filter(name=x).first()
category_queryset.append(category)
product.categories.set(category_queryset)

Categories