Django limits foreignkey value for records matching certain criteria

If I have a Book model that is foreignkeys Author , how can I limit what Authors is a valid foreignkey. For example, if Author contains a work_authored field, I want books to be accessible to foreigkey authors whose work_authored field work_authored set to “books” (verses of other meanings, such as “articles”, “essays”, play).

My scenario (and TL; DR): I want only other records of other objects that have a logical field equal to true to be available in my records.

I am sure that this can be done using Django's object validation , but this does not limit the values ​​in the Django admin drop-down list.

+4
source share
1 answer

Try using limit_choices_to . You can set it as

 class Book(Model): author = ForeignKey(AuthorModel, limit_choices_to = { 'work_authered': 'books'} ) 
+4
source

Source: https://habr.com/ru/post/1502007/


All Articles