【问题标题】:django ForeignKey field should only select by categorydjango ForeignKey 字段只能按类别选择
【发布时间】:2021-07-13 11:53:15
【问题描述】:

我的模型和Django admin and Django 表单中有一个 ForeignKey 字段,当我显示该字段或在 Django 管理员中时,我得到了该模型中的所有字段但是,我只想在该下拉列表中显示选定的字段,例如

class Area(models.Model):
    area_type_options = (('cc', 'Cost Center'), ('pc', 'Profit Center'),)
    name = models.CharField(max_length=100)
    area_type = models.CharField(max_length=100, choices=area_type_options)


class Item(models.Model):
    name = models.CharField(max_length=150, null=True, unique=True)
    profit_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='profit_center')
    cost_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='cost_center')

我可以看到cost_center 中的所有记录以及profit_center 中的所有记录,但是我只想查看area_type cc 到cost_center 的位置以及区域类型pc 到profit_center 的位置

请帮忙

【问题讨论】:

    标签: python django django-models django-views django-forms


    【解决方案1】:

    您可以使用ForeignKey.limit_choices_to [Django docs] 来执行此操作:

    class Item(models.Model):
        name = models.CharField(max_length=150, null=True, unique=True)
        profit_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='profit_center', limit_choices_to={'area_type': 'pc'})
        cost_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='cost_center', limit_choices_to={'area_type': 'cc')
    

    【讨论】:

      猜你喜欢
      • 2017-04-19
      • 2018-03-01
      • 2018-02-25
      • 2018-04-21
      • 1970-01-01
      • 2012-09-30
      • 2017-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多