为Django mod中的每个字段添加一个置信值

2024-04-16 23:26:12 发布

您现在位置:Python中文网/ 问答频道 /正文

想象一个django模型像一座建筑:

class Building(models.Model):
    address = models.CharField('address')
    age = models.IntegerField('age')

我想对每个字段都有一个置信值,例如,我90%确定地址是“768 5th Ave,New York”,但100%确定该建筑有30年历史。最好使用元组进行实例化,并为每个字段设置一个置信值:

>>> b = Building(
      address=("768 5th Ave, New York", 0.9),
      age=(34, 1.0))
>>> b.address
'768 5th Ave, New York'
>>> b.address.confidence
0.9

或者至少是这样:

>>> b.confidences['address']
0.9

我想将置信值应用于我当前的所有django模型,因此我正在寻找最优雅和通用的方法来实现这一点,希望对我已有的模型定义所做的更改最少。显然下面很难做到。。。你知道吗

class Building(models.Model):
    address = models.CharField('address')
    address_confidence = models.FloatField('address_confidence')

    age = models.IntegerField('age')
    age_confidence = models.FloatField('age_confidence')

一些我能想到但不确定的事情:

  • 有一个基础模型,为每个字段创建一个置信值(可能在init期间),然后将其作为我所有模型的基础,而不是模特。模特?你知道吗
  • 创建一个自定义字段,该字段具有置信值,并负责在读取/写入数据库时如何处理它?你知道吗
  • 另一个模型有一个置信域,并使用ForeignKey链接到它?你知道吗

谢谢你, 小时


Tags: django模型newagemodeladdressmodelsclass
3条回答

在你的情况下,我认为显式场更好。你知道吗

having a base model that creates a confidence value for each field (maybe during init) and then making that as the base of all my models instead of models.Model

这不是一个好主意,因为你不能通过模型一眼就知道所有的字段。你知道吗

Having another model with a confidence field and using ForeignKey to link to that

这种方法很重。您必须创建一个新表,并且与地址和年龄是一对一的关系,而创建新表则不是标准。和删除一条记录时,必须引用另一个表。你知道吗

creating a custom field which has confidence value and takes care of how it should be treated when reading/writing to database

这是更好的方法。你知道吗

如果您使用最新的Django和Postgres作为后端,那么可以使用HStoreField。它允许您以python dict()的形式存储数据

{'address': '768 5th Ave, New York', 'confidence': 0.9}

它是db中的单个字段,但具有极大的灵活性

另一个选项是ArrayField。但不能像标记HStoreField那样标记这些值。你知道吗

仅当您的后端是Postgres时,此功能才起作用

您可以将CharField和IntegerField子类化,为它们添加置信度属性,甚至可以创建自己的模型字段,如:

class CharConfidenceField(models.Model):
    text = models.CharField(max_length=80)
    confidence = model.IntegerField()

django文档展示了如何在此处创建自己的模型字段:

https://docs.djangoproject.com/en/1.8/howto/custom-model-fields/

相关问题 更多 >