I am new to Django and still learning, I have created a database and some models but I got stuck with meaningful labels in Django Admin. This is the model:
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
product_name = models.CharField(max_length= 50)
brand_name = models.CharField(max_length = 20)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
min_order = models.IntegerField()
max_order = models.IntegerField()
units = models.IntegerField()
quantity = models.ForeignKey(Quantity, on_delete=models.SET_NULL, null=True)
objects = ProductManager()
class Meta:
verbose_name = "Product"
verbose_name_plural = 'Products'
And I get this:
I want Product object (3) to be replaced byt the product_name. Thank you in advance!
You can override the __str__ method [python-doc] and return the product_name instead:
class Product(models.Model):
# …
def __str__(self):
return self.product_name
Related
In Django I have 2 models. One called Box and one called Product. A Box can have many different products and with different quantities of each product. For example box1 can have 1 productA and 2 productB.
My box model
class Box(models.Model):
boxName = models.CharField(max_length=255, blank = False)
product = models.ManyToManyField(Product)
def __str__(self):
return self.boxName
My product model
class Product(models.Model):
productName = models.CharField(max_length=200)
productDescription = models.TextField(blank=True)
productPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0)
class Meta:
db_table = 'products'
ordering = ['-productName']
def __str__(self):
return self.productName
How do I set up this model allowing me to select quantity of a products when creating the box object?
Define an intermediary model that contains product + quantity.
class Box(models.Model):
boxName = models.CharField(max_length=255, blank = False)
product_set = models.ManyToManyField(ProductSet)
def __str__(self):
return self.boxName
class ProductSet(models.Model):
quantity = models.PositiveIntegerField()
product = models.ForeignKey(Product, on_delete = models.PROTECT)
class Product(models.Model):
productName = models.CharField(max_length=200)
productDescription = models.TextField(blank=True)
productPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0)
class Meta:
db_table = 'products'
ordering = ['-productName']
def __str__(self):
return self.productName
So I have Article model and Category model. And below are my models.
class Category(models.Model):
objects = models.Manager()
category_kor = models.CharField(max_length=10, default="책")
category_eng = models.CharField(max_length=10, default="book")
def __str__(self):
return self.category
class Article(models.Model):
objects = models.Manager()
category_eng = models.ForeignKey(Category, on_delete=models.CASCADE, related_name = '', null=True, default=None)
category_kor = models.ForeignKey(Category, on_delete=models.CASCADE, related_name = '', null=True, default=None)
title = models.CharField(max_length = 100)
subtitle = models.CharField(max_length = 100)
url = models.URLField(max_length=10000)
def __str__(self):
return self.title
So I've done some research and noticed that I have to do something with the related_name but I cannot fully understand and apply it to my model. Please help. Thank you very much.
I think, Instead of using same value in related_field, if you use different value it should work.
class Article(models.Model):
objects = models.Manager()
category_eng = models.ForeignKey(Category, on_delete=models.CASCADE, related_name = 'rel_category', null=True, default=None)
category_kor = models.ForeignKey(Category, on_delete=models.CASCADE, related_name = 'related_category_kor', null=True, default=None)
title = models.CharField(max_length = 100)
subtitle = models.CharField(max_length = 100)
url = models.URLField(max_length=10000)
def __str__(self):
return self.title
I have a four models which each contains their own data. The models are:
Category (contains department_id foreign key)
Department (contains data, no foreign key)
ProductCategory (join table containing only product_id and category_id)
Product (contains data with no foreign key)
# models.py (excluded the rest for brevity)
from django.db import models
class Department(models.Model):
department_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
description = models.CharField(max_length=1000, blank=True, null=True)
class Meta:
managed = False
db_table = 'department'
class Category(models.Model):
category_id = models.AutoField(primary_key=True)
#department_id = models.IntegerField()
department = models.ForeignKey(Department, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
description = models.CharField(max_length=1000, blank=True, null=True)
class Meta:
managed = False
db_table = 'category'
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
description = models.CharField(max_length=1000)
price = models.DecimalField(max_digits=10, decimal_places=2)
discounted_price = models.DecimalField(max_digits=10, decimal_places=2)
image = models.CharField(max_length=150, blank=True, null=True)
image_2 = models.CharField(max_length=150, blank=True, null=True)
thumbnail = models.CharField(max_length=150, blank=True, null=True)
display = models.SmallIntegerField()
class Meta:
managed = False
db_table = 'product'
class ProductCategory(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
class Meta:
managed = False
db_table = 'product_category'
unique_together = (('product', 'category'),)
From my endpoint, I need to get all products in a department and return the response in the following format:
"rows": [
{
"product_id": integer,
"name": string,
"description": string,
"price": string,
"discounted_price": string,
"thumbnail": string
}
]
This is the endpoint:
path('products/inDepartment/<int:department_id>/', ProductViewSet.as_view({"get": "get_products_by_department"}))
How can I go about doing this? I'm stuck with the code below:
# products.py
def get_products_by_department(self, request, department_id):
"""
Get a list of Products of Departments
"""
categories = Category.objects.filter(department_id=department_id).values('category_id')
for item in categories:
category_id = item['category_id']
products = ProductCategory.objects.filter(category_id=category_id).values(
'product_id', name=F('product__name'), description=F('product__description'),
price=F('product__price'), discounted_price=F('product__discounted_price'), thumbnail=F('product__thumbnail'))
# Return response
if products.exists():
return Response(products, 200)
else:
return Response(products, 204)
The code above works and gives me the correct response but I'm not sure if I'm doing the query correctly? Should I be using a loop or is there a Django way to do it better without a loop?
Django's ORM allows for reverse relationship lookup.
https://docs.djangoproject.com/en/2.2/topics/db/queries/#lookups-that-span-relationships
categories = Category.objects.filter(department_id=department_id)
products = Product.objects.filter(productcategory__category__in=categories)
First i was getting an error like to create an explicit create method while serializing an array of product. So i added it but stiil im getting thhis error :
TypeError: 'customerorder' is an invalid keyword argument for this function
This is my serializers.py
class ProductSerializer(serializers.ModelSerializer):
product_id = serializers.IntegerField(required=False)
class Meta:
model = Product
fields = '__all__'
class CustOrderSerializer(serializers.ModelSerializer):
price = serializers.SlugRelatedField(slug_field='price', queryset=Price.objects.all())
# product = serializers.SlugRelatedField(slug_field='product', queryset=Product.objects.all())
area = serializers.SlugRelatedField(slug_field='address', queryset=Area.objects.all())
city = serializers.SlugRelatedField(slug_field='city', queryset=City.objects.all())
product = ProductSerializer(many=True)
class Meta:
model = CustOrder
fields = '__all__'
def create(self, validated_data):
product = validated_data.pop('product')
customerorder = CustOrder.objects.create(**validated_data)
for product in product:
Product.objects.create(**product, customerorder= customerorder)
return customerorder
This is models.py
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
product = ArrayField(models.CharField(max_length=200, blank=True))
def __str__(self):
return str(self.product)
class CustOrder(models.Model):
Customer_id = models.AutoField(primary_key=True)
CustomerName = models.CharField(max_length=200)
email = models.EmailField(max_length=70,blank=True, null= True, unique= True)
gender = models.CharField(max_length=6, choices=GENDER_CHOICES)
phone = PhoneField(null=False, blank=True, unique=True)
landmark = models.PointField()
#landmark = models.TextField(max_length=400, help_text="Enter the landmark", default='Enter landmark')
houseno = models.IntegerField(default=0)
#product_name = models.CharField(max_length=200, choices=PRODUCT_CHOICES,default='Boneless chicken')
# product_id = models.ForeignKey(Product, on_delete=models.CASCADE,related_name='custorder_productid')
product = models.ManyToManyField(Product, blank=True,related_name='pricetag')
quantity = models.IntegerField(default=0)
# price_id = models.ForeignKey(Price)
price = models.ForeignKey(Price, on_delete=models.SET_NULL, null=True,related_name='pricetag')
#price = models.DecimalField(max_digits=50, decimal_places=5, default=48.9)
pay_method = models.CharField(max_length=200,choices=PAYMENT_CHOICES, default='RAZOR PAY')
city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True)
area = models.ForeignKey(Area, on_delete=models.SET_NULL, null=True)
# Price.objects.aggregate(Sum('price'))
def __str__(self):
return self.CustomerName
There are several errors here.
Firstly for some reason you've set the related name from Product back to CustOrder as pricetag. That name does not appear to relate to either side of the relationship, so not sure why you've used it.
However even with that change, it still won't work, because you can't set many-to-many relationships at create time. You would need to create the product and then add it to the order.
But that still makes no sense, because you don't actually want to be creating products at all here; you want to add existing products to the order. So just do that:
customerorder = CustOrder.objects.create(**validated_data)
customerorder.product.add(*product)
Your Product model has not field customerorder. That is the reason why Django raises the error.
This is my first Django project and I am trying to implement add-to-cart features.
What changes should I make in this model so that multiple "Item" can be added into "Order", and also keep track of item quantity?
from django.db import models
from django.utils import timezone
# Create your models here.
class Order(models.Model):
customer = models.ForeignKey('Customer')
ordered_item = models.ForeignKey('OrderQuantity', on_delete=models.CASCADE, null=True)
address = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
class Customer(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
phone = models.CharField(max_length=50)
def __str__(self):
return self.first_name
class Item(models.Model):
name = models.CharField(max_length=50)
price = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
description = models.TextField(null=True)
summary = models.TextField(null=True)
type = models.CharField(max_length=50, null=True)
brand = models.CharField(max_length=50, null=True)
weight = models.DecimalField(default=0.00, max_digits=100, decimal_places=3)
picture = models.ImageField(null=True, upload_to='images/')
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
class OrderQuantity(models.Model):
product = models.ForeignKey('Item')
quantity = models.PositiveIntegerField()
You need to create ManyToManyField in Order Model
class Order(models.Model):
customer = models.ForeignKey('Customer')
ordered_item = models.ForeignKey('OrderQuantity', on_delete=models.CASCADE, null=True)
address = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
items = models.ManyToManyField(Item)
Then you can add items to order in this way:
someorder.items.add(someItem)
Use ManyToManyField in your Item Model
class Item(models.Model):
orders = models.ManyToManyField(Order)
---
So one item have many orders. You can access it by order.item_set or item.orders
It depends on what your Item model is.
If Item is contains a type of product - you may want to use many-to-many field in your Order model, like so:
class Order(models.Model):
...
items = models.ManyToManyField(Item)
...
If Item describes one real item (not type of items), the proper way would be using ForeignKey in your Item model:
class Item(models.Model):
...
order = models.ForeignKey(Order)
...