简体   繁体   English

布尔属性或新表(Django + PostgreSQL)

[英]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%. 数据比例:2%,15%,83%。 Amount query per time unit (in percent): 40%, 20%, 40% 每个时间单位的查询量(百分比):40%,20%,40%

I see some ways for resolve it in database: 我看到一些解决数据库中问题的方法:

  1. Boolean: is_test, is_premium. 布尔值:is_test,is_premium。 If we need only "Tests" book: Book.objects.filter(is_test=True) . 如果只需要“测试”书: 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. 单独的表格:books_test,books_premium,books_common。
  3. Choice field: string in ['Test', 'Premium', 'Common'] ; 选择字段: ['Test', 'Premium', 'Common']字符串;
  4. Combine 1 and 2: books_test table and books table with 'is_premium' attribute. 结合1和2:具有'is_premium'属性的books_test表和books表。

And we need optimally querying this data! 我们需要以最佳方式查询此数据! All three Book variants need in one page. 所有这三种Book变体都需要一页。 Exist queryset combinations: only tests, only common, common + premium, only premium. 现有查询集组合:仅测试,仅通用,通用+高级,仅高级。

  • If we use 1,3 variant: 1 endpoint with specific filter; 如果我们使用1,3个变体:1个具有特定过滤器的端点;
  • If we use 2 variant: one of the tree endpoints without filters (frontend should know what kind endpoint use). 如果我们使用2个变体:没有过滤器的树端点之一(前端应该知道使用哪种端点)。 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. 这样就为您提供了一个选择字段或一个包含选择的单独BookType模型。

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

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