【发布时间】:2021-01-29 11:24:55
【问题描述】:
使用 Django REST 框架我想知道是否可以将模型上 ManyToMany 字段的选项/选项限制为特定的 QuerySet?
使用下面的模型(向下滚动查看模型),我很好奇是否可以在模型定义中定义此限制,以实现以下目标:
# Having the following Employee instance
emp = Employee(...)
# Should return only the instances with value 'case' in EmployeeSubstitute.type field
emp.substitute_case.all()
# Should return only the instances with value 'phone' in EmployeeSubstitute.type field
emp.substitute_phone.all()
型号:
class Employee(models.Model):
substitute_case = models.ManyToMany(through=EmployeeSubstitute, ...)
substitute_phone = models.ManyToMany(through=EmployeeSubstitute, ...)
class EmployeeSubstitute(models.Model):
from = models.ForeignKey(Employee, ...)
to = models.ForeignKey(Employee, ...)
type = models.CharField(choices=..., ...) # choose between type 'case' and 'phone'
我看到有 limit_choices_to 参数,但这不是我想要的,因为它只会影响使用 ModelForm 或管理员时显示的选项。
【问题讨论】:
标签: django django-rest-framework