开发者

Additional computed fields in Model

I have two simple models in my Django app. Here's what they look like:

class Host(models.Model):
    url = models.URLField(max_length= 200)
    ssl = models.BooleanField(default = False)

class Query(models.Model):
    host = models.ForeignKey(Host)
    date = models.DateTimeField(auto_now_add = True)
    latency = models.FloatField(null = True)
    success = models.BooleanField(default = False)
    error = models.CharField(max_length= 2000, null = True)

When i access the Host model, I only have access to the two fields url开发者_Python百科 and ssl. When querying the Host model, I would like three extra fields to computed and returned dyanmicaly. These are the average_latency which would be the average of the not-null latency field of all the child Query records so i can access it something like this:

t = Tracker.objects.get(id = 1)
t.url
t.average_latency

Could someone please explain how I can do this or point me to some examples/documentation?

Thank you.


You can just use class properties:

class Host(models.Model):
    .
    .
    .
    @property
    def average_latency(self):
        # calculate latency from Query model ...
        return latency

Bear in mind that this is a read-only property.


You can check django-denorm, it's pretty much about what you're trying to achievie. I also have some flashbacks that there are other similar django apps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜