简体   繁体   English

Django自参考模型过滤器ForeignKey

[英]Django self referencing model filter ForeignKey

say i have following model in Django: 说我在Django中有以下模型:

class Category(models.Model):
    parent = models.ForeignKey('self', null=True, blank=True)

Is there a way to prevent referencing to same category? 有没有办法防止引用相同的类别? Right django generates select field in admin area where im able to select same category as parent. 正确的django会在管理区域中生成选择字段,其中无法选择与父项相同的类别。 Is there some way to filter that select in admin? 有什么方法可以过滤在admin中选择的内容?

Use ForeignKey.limit_choices_to - see documentation here 使用ForeignKey.limit_choices_to 在此处查看文档

You haven't provided enough of a code snippet to see how that would be done in your case, but I'm guessing on the parent ForeignKey, you'd want to limit the choices to a lambda function that checks to see if the name of the category is the same as the one doing the referencing. 您没有提供足够的代码片段来查看如何完成此操作,但是我猜测是在parent ForeignKey上,您希望将选择范围限制为一个lambda函数,以检查名称是否正确该类别的名称与进行引用的类别相同。

You probably want a lambda function here, not a single expression. 您可能需要一个lambda函数,而不是单个表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM