简体   繁体   中英

Should I use `property` or uneditable fields updated on save in Django models?

I'm learning Django while doing a basketball league management website, and I'm not sure how to tackle storing stats based on other stats.

For example there's Field Goal Percentage, which is Field Goals Made / Field Goals Attempted. From what I gathered there are three ways of 'storing it' in a model:

1) As a uneditable field which is calculated and updated on save

 fg_perc = models.FloatField(default=0, editable=False)

 def save(self, *args, **kwargs):
    self.fg_perc = round(self.fgm / self.fga, 3) * 100
    super(PlayerBoxscore, self).save(*args, **kwargs)

2) As a function

def fg_perc(self):
    if self.fga == 0:
        return "-"
    else:
        return round(self.fgm / self.fga, 3) * 100

3) As a property

def _fg_perc(self):
    if self.fga == 0:
        return "-"
    else:
        return round(self.fgm / self.fga, 3) * 100

fg_perc = property(_fg_perc)

Basically what I'm asking is which one is 'the best'.

What I'm thinking is, this data is not going to change frequently, and it will be viewed considerably often so the first option would be the best, because the data isn't calculated each time (like in other two examples). But I've seen people recommend using property , so I'm not sure.

And lately, what is the difference between 2) and 3)?

Thanks, Paweł

If you plan to use this data in the queries (for example for ordering) then go with the first option. Python functions are not available at database level.

If this data will be used only to displaying purposes then the property option is fine. This calculation is pretty cheap so there is no any performance issues. BTW you simplify it to:

@property
def fg_perc(self):
    return round(self.fgm / self.fga, 3) * 100 if self.fga else "-"

For those looking for an answer, I think I found the solution in Djangos @cached_property .

Source

Docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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