简体   繁体   中英

Boolean attribute or new table (Django + PostgreSQL)

Situation: I have a Books set. Book can be one of the types: "Test", "Premium" and "Common". Data proportional: 2%, 15%, 83%. Amount query per time unit (in percent): 40%, 20%, 40%

I see some ways for resolve it in database:

  1. Boolean: is_test, is_premium. If we need only "Tests" book: Book.objects.filter(is_test=True) . It is can be a proxy model, for example. Analogy for premium books;
  2. Separate Tables: books_test, books_premium, books_common.
  3. Choice field: string in ['Test', 'Premium', 'Common'] ;
  4. Combine 1 and 2: books_test table and books table with 'is_premium' attribute.

And we need optimally querying this data! All three Book variants need in one page. Exist queryset combinations: only tests, only common, common + premium, only premium.

  • If we use 1,3 variant: 1 endpoint with specific filter;
  • If we use 2 variant: one of the tree endpoints without filters (frontend should know what kind endpoint use). Or we can create one endpoint with some conditions and check by backend. Anyway: need extend logic;

Which way is more correct and why?

If you need to mix different types on one page, separate models/tables would complicate things for no good reason. The same goes for mapping more than two exclusive states to a combination of boolean fields.

This leaves you with a choice field or a separate BookType model containing the choices.

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