You need to enable JavaScript to run this app. Django如何为含多个外键的模型编写高效可维护的测试
优惠活动
大模型
产品
解决方案
定价
更多

Django如何为含多个外键的模型编写高效可维护的测试

模型结构优化建议

你当前的多对多中介表结构设计本身是合理的,符合需要给关联关系附加额外字段(这里是value)的场景,只需要做几处小调整降低后续维护成本:

  • 修正反向关联命名:当前related_name的命名容易产生歧义,建议调整为
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="product_values")
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="category_values")
    
    后续调用product.category_values.all()就能直接拿到该产品关联的所有分类值,语义清晰很多。
  • 补全缺失字段:你的测试代码里用到了Category的selection_type字段,但模型定义里没有声明,需要补上:
    class Category(models.Model):
        name = models.CharField(max_length=100)
        selection_type = models.CharField(max_length=20) # 新增字段
    
  • 替换过时的唯一性约束写法:Django官方已经标记unique_together为可能弃用的语法,推荐用UniqueConstraint代替:
    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['category', 'product'], name='unique_product_category_pair')
        ]
    
测试写法优化方案

你当前的setUp写法是可运行的,但属于硬编码的一次性写法,后续测试用例变多之后维护成本会非常高,推荐两种业内常用的标准化高效写法:

方案1:使用测试工厂(最推荐的工程化方案)

用factory_boy库封装所有模型的创建逻辑,后续修改模型字段只要调整工厂定义,不需要修改所有测试用例的创建代码:

  1. 先在项目里新增factories.py:
import factory
from .models import Product, Category, ProductCategoryValue

class ProductFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Product
    name = factory.Faker('word') # 支持自动生成随机测试值

class CategoryFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Category
    name = factory.Faker('word')
    selection_type = factory.Iterator(['bullets', 'text', 'Boolean']) # 自动遍历预设枚举值

class ProductCategoryValueFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = ProductCategoryValue
    value = factory.Faker('sentence', nb_words=2)
    # 自动创建关联外键实例,不需要手动提前构造
    product = factory.SubFactory(ProductFactory)
    category = factory.SubFactory(CategoryFactory)
  1. 调整测试代码的setUp:
from django.test import TestCase
from .factories import ProductFactory, CategoryFactory, ProductCategoryValueFactory

class ProductCategoryTest(TestCase):
    def setUp(self):
        # 需要固定值的场景手动传参,其他参数用工厂的默认随机值即可
        self.product_touch = ProductFactory(name="Touchscreen")
        self.product_dancer = ProductFactory(name="Dancer")
        self.category_usecase = CategoryFactory(name="Use Case", selection_type="bullets")
        self.category_video = CategoryFactory(name="Video Conferencing", selection_type="text")
        self.category_multisite = CategoryFactory(name="Multisite", selection_type="Boolean")
        self.pc_value = ProductCategoryValueFactory(value="foobar", product=self.product_touch, category=self.category_usecase)

方案2:原生Django无依赖优化

如果不想引入第三方库,可以把重复的创建逻辑封装为测试类的工具方法,减少重复代码:

from django.test import TestCase
from .models import Product, Category, ProductCategoryValue

class ProductCategoryTest(TestCase):
    def create_product(self, name="Default Product"):
        return Product.objects.create(name=name)
    
    def create_category(self, name="Default Category", selection_type="text"):
        return Category.objects.create(name=name, selection_type=selection_type)
    
    def create_pc_value(self, value="default", product=None, category=None):
        product = product or self.create_product()
        category = category or self.create_category()
        return ProductCategoryValue.objects.create(value=value, product=product, category=category)

    def setUp(self):
        self.product_touch = self.create_product(name="Touchscreen")
        self.product_dancer = self.create_product(name="Dancer")
        self.category_usecase = self.create_category(name="Use Case", selection_type="bullets")
        self.category_video = self.create_category(name="Video Conferencing", selection_type="text")
        self.category_multisite = self.create_category(name="Multisite", selection_type="Boolean")
        self.pc_value = self.create_pc_value(value="foobar", product=self.product_touch, category=self.category_usecase)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 21:06:01