临时数据库的Django自定义创建管理器逻辑 [英] Django custom creation manager logic for temporal database

查看:299
本文介绍了临时数据库的Django自定义创建管理器逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开发一个Django应用程序,该应用程序具有围绕对象的时间状态的内置逻辑.期望能够具有表示资源的单个对象,同时具有该资源的属性能够随时间变化.例如,理想的用例是在任何给定时间(去年,昨天,明天,明年...)查询资源的owner.

I am trying to develop a Django application that has built-in logic around temporal states for objects. The desire is to be able to have a singular object representing a resource, while having attributes of that resource be able to change over time. For example, a desired use case is to query the owner of a resource at any given time (last year, yesterday, tomorrow, next year, ...).

这就是我正在工作的...

Here is what I am working with...

class Resource(models.Model):                                       
    id = models.AutoField(primary_key=True)                         


class ResourceState(models.Model):                                  
    id = models.AutoField(primary_key=True)                         

    # Link the resource this state is applied to                    
    resource = models.ForeignKey(Resource, related_name='states', on_delete=models.CASCADE)

    # Track when this state is ACTIVE on a resource                 
    start_dt = models.DateTimeField()                               
    end_dt = models.DateTimeField()                                 

    # Temporal fields, can change between ResourceStates      
    owner = models.CharField(max_length=100)                        
    description = models.TextField(max_length=500)                 

我觉得我将不得不创建一个自定义界面来与该状态进行交互.一些示例用例(界面完全悬而未决)...

I feel like I am going to have to create a custom interface to interact with this state. Some example use cases (interface is completely up in the air)...

# Get all of the states that were ever active on resource 1 (this is already possible)
Resource.objects.get(id=1).states.objects.all()

# Get the owner of resource 1 from the state that was active yesterday, this is non-standard behavior
Resource.objects.get(id=1).states.at(YESTERDAY).owner

# Create a new state for resource 1, active between tomorrow and infinity (None == infinity)
# This is obviously non standard if I want to enforce one-state-per-timepoint
Resource.objects.get(id=1).states.create(
    start_dt=TOMORROW,
    end_dt=None,
    owner="New Owner",
    description="New Description"
)

我感觉将需要大量的定制逻辑来进行创建. 我要强制在任何给定时间点在Resource上只能激活一个ResourceState.

I feel the largest amount of custom logic will be required to do creates. I want to enforce that only one ResourceState can be active on a Resource for any given timepoint. This means that to create some ResourceState objects, I will need to adjust/remove others.

>> resource = Resource.objects.get(id=1)
>> resource.states.objects.all()
[ResourceState(start_dt=None, end_dt=None, owner='owner1')]
>> resource.states.create(start_dt=YESTERDAY, end_dt=TOMORROW, owner='owner2')
>> resource.states.objects.all()
[
    ResourceState(start_dt=None, end_dt=YESTERDAY, owner='owner1'),
    ResourceState(start_dt=YESTERDAY, end_dt=TOMORROW, owner='owner2'), 
    ResourceState(start_dt=TOMORROW, end_dt=None, owner='owner1')
]

我知道我将不得不围绕定义逻辑进行大部分工作,但是应该在任何直观的地方放置它吗? Django是否为我提供了方便的位置来创建这些方法?如果是这样,在哪里应用它们的最佳位置?针对Resource对象?使用自定义Manager处理与相关"ResourceState"对象的交互?

I know I will have to do most of the legwork around defining the logic, but is there any intuitive place where I should put it? Does Django provide an easy place for me to create these methods? If so, where is the best place to apply them? Against the Resource object? Using a custom Manager to deal with interacting with related 'ResourceState' objects?

重新阅读上面的内容有点令人困惑,但这也不是一个简单的话题!!请让我知道是否有人对上述方法有任何想法!

Re-reading the above it is a bit confusing, but this isnt a simple topic either!! Please let me know if anyone has any ideas for how to do something like the above!

一吨!

推荐答案

对于评论太长时间了,纯粹是一些想法,不是完整的答案,但是已经处理了金融系统中许多有效日期记录(在Django中不是)事情浮现在脑海:

too long for a comment, and purely some thoughts, not a full answer, but having dealt with many date effective records in financial systems (not in Django) some things come to mind:

我的直觉是将其放在资源模型的save方法上.您可能也需要定制管理器.

My gut would be to start by putting it on the save method of the resource model. You are probably right in needing a custom manager as well.

我可能还会调侃状态模型中is_current布尔字段的想法,但是将来日期有效的状态记录需要考虑某些注意事项.如果一次只有一个活动状态,我还将检查是否需要结束日期.同时具有开始和结束绝对可以简化原始sql查询(如果需要的话):date() between state.start and state.end<-这将提供当前记录,任意日期的sub都可以获取该日期的有效记录.另外,在您不知道结束日期的情况下,请考虑开放结束日期.您的查询将必须正确处理空值.您可能还需要考虑开放结束日期(例如,对于未知起始日期的大量历史数据).我建议您不要使用某些超级早期日期作为填充(对于未知的结束日期,该日期与将来的日期相同)-如果您进行了大量交易,则查询优化器可能会谢谢您,但是,我可能会变老了,这不再重要了.

I'd probably also flirt with the idea of a is_current boolean field in the state model but certain care would need to be considered with future date effective state records. If there is only one active state at a time, I'd also examine the need for an enddate. Having both start and end definitely makes the raw sql queries (if ever needed) easier: date() between state.start and state.end <- this would give current record, sub in any date to get that date's effective record. Also, give some consideration to the open ended end date where you don't know the end date date. Your queries will have to handle the nulls properly. YOu probably also may need to consider the open ended start date (say for a load of historical data where the original start date is unknown). I'd suggest staying away from using some super early date as a fill in (same for date far in the future for unknown end dates) - If you end up with lots of transactions, your query optimizer may thank you, however, I may be old and this doesn't matter anymore.

如果您想阅读有关这些内容的信息,建议您阅读 https://www.amazon.ca/Art-SQL-Stephane-Faroult/dp/0596008945/和第6章:

If you like to read about this stuff, I'd recommend a look at 1.8 in https://www.amazon.ca/Art-SQL-Stephane-Faroult/dp/0596008945/ and chapter 6:

但是在解决一个解决方案之前,我们必须承认 评估表有各种形状和大小.例如, 处理大量数据的电信公司拥有 相对短的价格表,不会经常更改.经过 相反,一家投资银行会存储所有证券的新价格, 衍生产品,以及它可能处理的任何类型的金融产品 几乎是连续的.在一种情况下,好的解决方案并不一定 成为另一个很好的解决方案.

"But before settling for one solution, we must acknowledge that valuation tables come in all shapes and sizes. For instance, those of telecom companies, which handle tremendous amounts of data, have a relatively short price list that doesn't change very often. By contrast, an investment bank stores new prices for all the securities, derivatives, and any type of financial product it may be dealing with almost continuously. A good solution in one case will not necessarily be a good solution in another.

处理既累积又变化的数据需要非常小心 设计和策略随变化率而变化."

Handling data that both accumulates and changes requires very careful design and tactics that vary according to the rate of change."

这篇关于临时数据库的Django自定义创建管理器逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆