I have a product category here is the model:
class ProductCategory(models.Model):
name = models.CharField(max_length=50)
description = models.TextField(max_length=300, null=True, blank=True)
parent = models.ForeignKey('self', null=True, blank=True, related_name='sub_categories', on_delete=models.CASCADE)
image = models.ImageField(upload_to=product_category_path, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at")
updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at")
class Meta:
verbose_name = "product category"
verbose_name_plural = "product categories"
db_table = "product_categories"
ordering = ['name']
def __str__(self):
return str(self.name)
def can_be_deleted(self):
return self.name != "uncategorized"
def delete(self, *args, **kwargs):
if self.can_be_deleted():
super().delete(*args, **kwargs)
else:
raise Exception("This category cannot be deleted.")
def get_descendants(self):
descendants = []
children = self.sub_categories.all()
for child in children:
descendants.append(child)
descendants.extend(child.get_descendants())
return descendants
Here is the admin of the products app:
from django.contrib import admin
from .models import *
from import_export import resources
from import_export.admin import ImportExportModelAdmin
class CategoryResource(resources.ModelResource):
class Meta:
model = ProductCategory
fields = ("id", "name", "description", "parent")
class ProductCategoryAdmin(ImportExportModelAdmin):
list_display = ("name", "id", "parent")
search_fields = ["name", "id"]
resource_class = CategoryResource
class BrandResource(resources.ModelResource):
class Meta:
model = Brand
fields = ("name", "category")
class BrandAdmin(ImportExportModelAdmin):
list_display = ("name", "category")
search_fields = ["name", "category"]
resource_class = [BrandResource]
class ProductResource(resources.ModelResource):
class Meta:
model = Product
fields = (
"id",
"title",
"description",
"price",
"color",
"height",
"width",
"length",
"weight",
"material",
"digital",
"condition",
"cordless",
"hand_made",
"power_usage",
"device_storage",
"ram",
"screen_size",
"cpu",
"gpu",
"size",
"capacity",
"age",
"type",
"gender",
"sports",
"business",
"brand",
"user",
"sale",
)
class ProductAdmin(ImportExportModelAdmin):
list_display = ("title", "category", "price", "business")
search_fields = ["title", "category"]
resource_classes = [ProductResource]
class ProductImageAdmin(admin.ModelAdmin):
list_display = ("product", "image")
search_fields = ["gallery"]
class ProductVideoAdmin(admin.ModelAdmin):
list_display = ("product", "video")
search_fields = ["product"]
class CartItemAdmin(admin.ModelAdmin):
list_display = ('cart', 'product', 'quantity', 'total_price')
search_fields = ['cart__user__username', 'product__title']
list_filter = ['cart__user', 'product']
def total_price(self, obj):
return obj.total_price()
total_price.short_description = 'Total Price'
class CartItemInline(admin.TabularInline):
model = CartItem
extra = 0
readonly_fields = ['total_price']
fields = ['product', 'quantity', 'total_price']
def total_price(self, obj):
if obj.product and obj.quantity:
return obj.product.price * obj.quantity
return 0
total_price.short_description = 'Total Price'
def get_extra(self, request, obj=None, **kwargs):
return 1
def has_add_permission(self, request, obj):
return obj is not None
class UserCartAdmin(admin.ModelAdmin):
list_display = ("user", "display_items")
search_fields = ["user"]
inlines = [CartItemInline]
def display_items(self, obj):
items = obj.items.all()
return ", ".join([f"{item.quantity} x {item.product.title}" for item in items])
display_items.short_description = 'Items in Cart'
admin.site.register(Product, ProductAdmin)
admin.site.register(ProductCategory, ProductCategoryAdmin)
admin.site.register(Brand, BrandAdmin)
admin.site.register(ProductImage, ProductImageAdmin)
admin.site.register(ProductVideo, ProductVideoAdmin)
admin.site.register(CartItem, CartItemAdmin)
admin.site.register(Cart, UserCartAdmin)
I am trying to import categories from a csv file whose headings are id, name, description, parent. If I import the categories I get an error:
- Line number: 29 - ProductCategory matching query does not exist.
and it is because Django keep a sequence running of ids. So if I have a product with id 1 and I delete that product and create a new one then the new product id will be 2 not 1 and this is a problem when importing categories because the parent id determines where a child category will sit. If I reset the sequence with this SQL statements on the product_categories table:
ALTER SEQUENCE product_categories_id_seq RESTART;
then I can import the categories and it shows 28 new ones where created but there 259 and no categories are actually created because there are no categories displayed in the Django admin.
But even after resetting a newly created category starts at 32 and not 1 why is that?