You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于JSON数据构建Dart/Flutter中商品与分类的关联关系

解决商品与分类关联并在ListView显示分类名称的方案

1. 建立模型关联关系

确保Product与Category通过外键建立一对多关联(一个分类对应多个商品):

# models.py
from django.db import models

class Category(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=100)
    # 补充categories.json中的其他字段,如描述、排序权重等

    def __str__(self):
        return self.name

class Product(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=200)
    # 外键关联Category,on_delete根据业务需求选择CASCADE/PROTECT等
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products')
    # 补充listing.json中的其他字段,如价格、库存、封面图等

    def __str__(self):
        return self.name

注:若JSON中的分类ID为字符串类型,需将Category.id改为CharField类型。

2. 导入JSON数据到模型

先导入分类数据(避免商品因找不到关联分类报错),再导入商品数据:

# 可在Django Shell中执行,或封装为自定义管理命令
import json
from your_app_name.models import Category, Product

# 导入分类数据
with open('categories.json', 'r', encoding='utf-8') as f:
    category_list = json.load(f)
for item in category_list:
    Category.objects.get_or_create(
        id=item['id'],
        defaults={'name': item['name']}
        # 其他字段对应item中的键值对
    )

# 导入商品数据
with open('listing.json', 'r', encoding='utf-8') as f:
    product_list = json.load(f)
for item in product_list:
    # 通过分类ID获取关联的Category实例
    category = Category.objects.get(id=item['category_id'])
    Product.objects.get_or_create(
        id=item['id'],
        defaults={
            'name': item['name'],
            'category': category
            # 其他字段对应item中的键值对
        }
    )

3. 配置ListView并渲染分类名称

定义ListView视图

# views.py
from django.views.generic import ListView
from .models import Product

class ProductListView(ListView):
    model = Product
    template_name = 'products/product_list.html'  # 替换为你的模板路径
    context_object_name = 'product_list'  # 模板中使用的变量名,可选

在模板中显示分类名称

直接通过外键关联访问分类名称:

<!-- products/product_list.html -->
<div class="product-container">
    {% for product in product_list %}
        <div class="product-item">
            <h3>{{ product.name }}</h3>
            <p>分类:{{ product.category.name }}</p>
            <!-- 渲染其他商品信息 -->
        </div>
    {% empty %}
        <p>暂无商品数据</p>
    {% endfor %}
</div>

已有数据的迁移处理(若之前已导入商品但未关联分类)

如果已经导入商品数据,仅需补充分类关联:

  1. 给Product模型添加允许为空的外键字段,执行迁移:
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True)
python manage.py makemigrations
python manage.py migrate
  1. 批量更新商品的分类关联:
from your_app_name.models import Product, Category
for product in Product.objects.all():
    try:
        cat = Category.objects.get(id=product.category_id)
        product.category = cat
        product.save()
    except Category.DoesNotExist:
        # 处理找不到对应分类的情况,如标记为"未分类"
        pass
  1. 删除原category_id字段,再次执行迁移。

内容的提问来源于stack exchange,提问作者Abdoulaye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 14:16:45