I want to make a model with products that will have a subcategory that will fall into its category.
Here is an example: outerwear (category) -> t-shirt (subcategory) -> White t-shirt with a pattern (product)
But I was faced with the problem that the name of the subcategory is not displayed in the product.
My models.py
class Global_category(models.Model):
Name = models.CharField(max_length=20, verbose_name='Имя')
slug = models.SlugField(max_length=20, verbose_name='Slug', unique=True)
class Meta:
ordering = ['Name']
verbose_name = 'Категория'
verbose_name_plural = 'Категории'
def __str__(self):
return self.Name
class SubCategory(models.Model):
Name = models.CharField(max_length=20, verbose_name='Имя подкатегории')
slug = models.SlugField(max_length=20, verbose_name='Slug', unique=True)
Global_category = models.ForeignKey(Global_category, on_delete=models.CASCADE, verbose_name='Имя Категории')
class Meta:
ordering = ['Name']
verbose_name = 'Подкатегория'
verbose_name_plural = 'Подкатегории'
class Product(models.Model):
Category = models.ForeignKey(SubCategory, on_delete=models.CASCADE, default=None)
I will be glad to any help
Just add it to your model SubCategory
def __str__(self):
return self.name
django.db.models.Model.str
Related
I dont want any foreign keys directly in my users table, and by default, when I add a foreing key field in my custom User model, Django generate 2 tabels like this:
When I add a many-to-many field in my Company model I get the 3 desired tables but it's made possible for the same user be in two different companys.
class Company(models.Model):
class Meta:
verbose_name = 'Company'
verbose_name_plural = 'Companys'
ordering = ['name']
db_table = 'companys'
id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, unique=True, verbose_name='ID Empresa')
name = models.CharField(max_length=100, verbose_name='Nome')
users = models.ManyToManyField(User, related_name='company', verbose_name='Users')
def __str__(self):
return self.name
I want Django to generate an additional table with only the Foreing Keys of the two models but keep the behevior of a many-to-one relationship between the two. like this:
you can make your third table by using a separate model
class Company(models.Model):
class Meta:
verbose_name = 'Company'
verbose_name_plural = 'Companys'
ordering = ['name']
db_table = 'companys'
id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, unique=True, verbose_name='ID Empresa')
name = models.CharField(max_length=100, verbose_name='Nome')
def __str__(self):
return self.name
class UserCompanyRelationModel(models.Model):
class Meta:
db_table = 'usr_comp'
user = models.OneToOneField(User, on_delete=models.CASCADE)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
My models, category and product. Each product has a category field, which is linked through ForeignKey.
class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
description = models.TextField()
image = models.ImageField(upload_to='category', blank=True)
class Meta:
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=50, unique=True)
description = models.TextField()
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category')
price = models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='product', blank=True)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
update = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = 'product'
verbose_name_plural = 'products'
def __str__(self):
return self.name
And views, a product category can be selected and when I click on a category, I want the product to appear only in that category
class CategoriesList(LoginRequiredMixin, ListView):
login_url = 'login/'
template_name = 'index.html'
model = Category
class ProductsList(ListView):
template_name = 'products.html'
model = Product
def get_queryset(self):
return super().get_queryset().filter(category=category_id)
In Models:
class ShopCategory(models.Model):
category = models.CharField(max_length=100)
class Meta:
db_table = "tbl_ShopCategory"
class Shop(models.Model):
id_shop = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=200)
slug = models.SlugField(max_length=250, blank=True, null=True)
cover_img = models.CharField(max_length=250, blank=True)
category = models.ForeignKey(ShopCategory, on_delete=models.CASCADE)
avgscore = models.FloatField(default=0)
I want to show the Category name?
...........................................................
Add an str method to your ShopCategory model:
class ShopCategory(models.Model):
category = models.CharField(max_length=100)
def __str__(self):
return self.category
class Meta:
db_table = "tbl_ShopCategory"
Here is my models.py:
class Category(models.Model):
category = models.CharField(max_length=50, verbose_name=u"文章分类", default="")
add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")
class Meta:
verbose_name = u"文章分类"
verbose_name_plural = verbose_name
def __unicode__(self):
return self.category
class Article(models.Model):
category = models.ForeignKey(Category, verbose_name=u"文章分类")
title = models.CharField(max_length=100, verbose_name=u"文章题目", default="")
content = UEditorField(width=1000, height=500,imagePath="media/", filePath="media/",verbose_name=u"文章内容")
read_nums = models.IntegerField(default=0, verbose_name=u"阅读量")
comment_nums = models.IntegerField(default=0, verbose_name=u"评论数")
add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")
class Meta:
verbose_name = u"文章"
verbose_name_plural = verbose_name
def __unicode__(self):
return self.title
Now I need to show how many articles in category at django-admin page, in this page:
How should I do?
You can add custom columns via the list_display of your admin class. There you can just add a method that you add to your model (or the admin) and that returns the desired value:
class Category(models.Model):
# ...
def article_count(self):
return self.article_set.count()
article_count.short_description = 'Number of articles' # displayed as label/column header
class CategoryAdmin(admin.ModelAdmin):
readonly_fields = ['article_count'] # this is your custom method
list_display = ['__str__', 'article_count', 'add_time']
admin.site.register(Category, CategoryAdmin)
I have an entity of Products, category and sub-category. A category can have many products and also a category can have many sub-categories. For example a product called Iphone-4 can fall on smart phone subcategories of Electronics & Gadgets Category. Similiary samsung product can fall on same smart-phone sub-categories of Electronics&Gadgets Category. How could i show this relation effectively?
Here is what i did
class Category(models.Model):
name = models.CharField(max_length=80, null=True)
parent = models.ForeignKey('self', blank=True, null=True, related_name="children")
class Meta:
unique_together = ('parent',)
verbose_name = 'Category'
verbose_name_plural = 'Categories'
class Product(models.Model):
token = models.CharField(default=token_generator, max_length=20, unique=True, editable=False)
category = models.ForeignKey(Category)
company = models.ForeignKey(Company, related_name="company_product")
name = models.CharField(max_length=200, null=True)
model = models.CharField(max_length=100, blank=True, null=True)
specification = models.TextField(null=True, blank=True)
price = models.PositiveIntegerField(default=0)
admin.py
class ProductAdmin(admin.ModelAdmin):
list_select_related = ('category', 'company',)
class Meta:
model = Product
class CategoryAdmin(admin.ModelAdmin):
list_select_related = ('parent',)
list_display = ('name', 'parent', )
class Meta:
model = Category
This way in my admin, the categories and sub-categories are shown so vaguely. Category Electronics & Gadgets is shown multiple times. It is shown as per the number of sub-category that falls under this category.
Is this expected behavior or has to handle this other effective way?
Here is the code snippet to list nested Category and Sub-Category inside the Admin Panel. Please register the Category model in the admin.py of your application first.
# Category Model.
class Category(models.Model):
name = models.CharField(blank=False, max_length=200)
slug = models.SlugField(null=False)
parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.SET_NULL)
class Meta:
db_table = "dj_categories"
# Add verbose name
verbose_name = 'Category'
verbose_name_plural = "Categories"
unique_together = ('slug', 'parent',)
def __str__(self):
return self.name