Integer field sum in model



  • There's a model, for example.

    t1 = models.IntegerField(...)
    t2 = ...
    t3 = ...
    t1name = models.CharField(...)
    t2name = ...
    ...
    

    t1, t2, t(n) - figures. I'm making a sample from the base on 1 site and it's only necessary to count the amount of these fields (t(n)) He whispered the hat that I don't have to do that:

    a = Quote.objects.filter(user__username=Fool).order_by('-id')[0]
    itog= a.t1 + a.t2 + a.t3 ....
    


  • I'll do it a little, so it's clearer. Let's say we have a model.

    class MyModel(models.Model):
        t1 = models.IntegerField(...)
        t2 = ...
        t3 = ...
        t1name = models.CharField(...)
        t2name = ...
    

    We get one object. obj = MyModel.objects.get(id=1)♪ Then we'll work exactly with these symbols.

    In django, all service information about the fields falls down MyModel._meta.fields♪ Accordingly, the challenge is to filter this list in search of the fields we need, then get their meanings and give it up. Dynamicly, you can get through the fields, like all the python. getattr♪ Well, let's set an example.

    We'll try to get it first. t1

    >>> [field for field in MyModel._meta.fields if field.name == 't1']
    [<django.db.models.fields.IntegerField: t1>]
    

    All right, it's working. But we have to get all t. Let's write a regular.

    And it'll be one more problem.

    import re
    >>> [field for field in MyModel._meta.fields if re.match(r'^t\d+$', field.name)]
    [<django.db.models.fields.IntegerField: t1>, <django.db.models.fields.IntegerField: t2>, <django.db.models.fields.IntegerField: t3>, <django.db.models.fields.IntegerField: t4>]
    

    The regular picks up all fields that start on. t And then one or more numbers go.

    Suddenly we won't. IntegerField? Let's do another field check:

    >>> [field for field in MyModel._meta.fields if re.match(r'^t\d+$', field.name) and field.get_internal_type() == 'IntegerField']
    [<django.db.models.fields.IntegerField: t1>, <django.db.models.fields.IntegerField: t2>, <django.db.models.fields.IntegerField: t3>, <django.db.models.fields.IntegerField: t4>]
    

    Now nobody's gonna lie to us. All we have to do is cumulate the values from these fields and add this as a model copy method:

    def sum_f_fields(self):
        field_names = [field for field in MyModel._meta.fields if re.match(r'^t\d+$', field.name) and field.get_internal_type() == 'IntegerField']
        values = [getattr(self, field.name, None) or 0 for field in field_names]
        returm sum(values)
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2