简体   繁体   中英

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. 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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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