简体   繁体   English

如何设置Django模型字段的NoData值

[英]How to set a Django model field's NoData value

I just realized that the dataset I uploaded to Django model has a field (call it 'A') with "-999" which indicates NoData. 我刚刚意识到,我上传到Django模型的数据集包含一个带有“ -999”的字段(称为“ A”),表示NoData。 This is throwing off my calculations, but I don't want to totally exclude these objects from my filters, just for calculations, for example: objects.aggregate(Avg('A')). 这使我无法进行计算,但是我不想完全将这些对象从过滤器中排除,仅用于计算,例如:objects.aggregate(Avg('A'))。

How do I tell my Django model to treat this value as the NoData for field A? 如何告诉我的Django模型将此值视为字段A的NoData? I see null=True tells Django to store empty values as NoData, but what if it should store Null when the values = -999. 我看到null = True告诉Django将空值存储为NoData,但是当值= -999时如果应该存储Null怎么办。

If there is not a straightforward way, is the best/most efficient way just to use exclude() whenever I make these calculations? 如果没有直接的方法,最好/最有效的方法是在我进行这些计算时仅使用exclude()吗? Or maybe I should do some sort of replace in my database to convert -999 in field A to Null (how?). 或者,也许我应该在数据库中进行某种替换,以将字段A中的-999转换为Null(如何?)。 I thank you 我谢谢你

A quick solution would be to use exclude in your aggregate queries: 一个快速的解决方案是在聚合查询中使用exclude

YourModel.objects.exclude(a=-999).aggregate(Avg('a'))

If you wanted to replace the -999 values with None : 如果要将-999值替换为None

  1. Adjust your Model field with the correct parameters (eg: null=True) 使用正确的参数调整您的“模型”字段(例如:null = True)
  2. Do a schema migration 进行架构迁移
  3. Do a Data Migration 进行数据迁移

The data migration would need to call a function something like: 数据迁移将需要调用以下函数:

def update_nodata(apps, schema_editor):
    YourModel = apps.get_model('yourappname', 'YourModel')
    for obj in YourModel.objects.filter(a=-999):
        obj.a = None
        obj.save()

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

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