简体   繁体   English

限制外键 Django 的模型选择

[英]Limit model choices on foreign key Django

I have the following field我有以下字段

target_contenttype = models.ForeignKey(ContentType,
                                       blank=True,
                                       null=True,
                                       related_name="target_object",
                                       on_delete=models.PROTECT,
                                       limit_choices_to={'model__in':(
                                           ''        
                                       )})

On limit_choices_to i can't find the documentation on how to limit related model located on different app.在 limit_choices_to 上,我找不到有关如何限制位于不同应用程序上的相关模型的文档。 Can someone help.有人可以帮忙吗。

You can either use get_for_model() (if you have imported the related models) or get_by_natural_key() , passing it the app name and the model name, both in lowercase:您可以使用get_for_model() (如果您已导入相关模型)或get_by_natural_key() ,将应用程序名称和模型名称传递给它,两者均为小写:

from relatedapp.models import RelatedModel

limit_choices_to={'model__in':(
    ContentType.objects.get_for_model(RelatedModel),
    ContentType.objects.get_by_natural_key('relatedapp', 'relatedmodel'),
)}

Another way would be to create a Q object to filter on app label + model, both in lowercase:另一种方法是创建一个 Q 对象来过滤应用程序标签 + 模型,两者都是小写的:

limit_choices_to=(
    Q(app_label='app1', model='model1') | 
    Q(app_label='app2', model='model2')
)

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

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