Django;将子范畴限定到某个主范畴

2024-06-16 10:52:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个相当简单的问题,我可以通过执行查询动态获取CHOICES来实现,但我想知道在Django中是否有更“本地”的方法来实现这一点

告诉我这个

class Item(models.Model):

    name = name = models.CharField(max_length = 75)
    sub_category = models.ForeignKey('ItemSubcategory')

这就是等级制度的一个例子

  • 类别:食品
    • 子类别:面包
      • 商品:虎面包
      • 商品:黑面包
      • 商品:白面包

这个逻辑是可以的,但对于某些其他模型,我想这样使用它

class Item(models.Model):

    name = name = models.CharField(max_length = 75)
    sub_category = models.ForeignKey('ItemSubcategory', limit_to=('ItemCategory', 'Food'))

所以它会限制我使用的下拉/过滤器,只显示食品子类别,而不是其他类别下的所有其他子类别。你知道吗


Tags: name食品modelmodelsitem类别lengthmax
1条回答
网友
1楼 · 发布于 2024-06-16 10:52:26

可以使用limit_choices_to参数:https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to

class Item(models.Model):

    name = name = models.CharField(max_length = 75)
    sub_category = models.ForeignKey(
        'ItemSubcategory', 
        limit_choices_to={'ItemCategory': 'Food'}
    )

只是给你一个基本的想法。你知道吗

相关问题 更多 >