Using generators in Django

onlinejudge95 onlinejudge95 at gmail.com
Thu Dec 19 01:32:28 EST 2019


Hi Devs,

A quick question. I am using Django to schedule some commands to populate
my PostgreSQL(Apart from using it as a web framework). I am currently
fetching records from a particular table and for each of those records
doing some calculation and storing the processed data in some other
database. The skeleton code looks like this

```
...
def fetch_needs(project_id):
    for item in MyNeedsModel.filter(project_id=project_id).all():
        yield item
...

class Command(django.core.management.base.BaseCommand):
    def add_argument(self, parser):
        ...
    def handler(self, *args, **kwargs):
        project = (args[0], args[1])
        project_id = MyProject.filter(...).id
        for need in fetch_needs(project_id):
            ....
```

I need to know whether the use of generators is correct here, in the sense
that would it have any performance issues. The point that I am having
trouble understanding is a comment on my code review.

Also don’t use generator you are bypassing django inbuilt caching
> mechanism. Using integrator it will create another list and get them one by
> one


Any help would be appreciated.

Thanks,
onlinejudge95


More information about the Python-list mailing list