#27408: Make QuerySet.bulk_create() populate fields on related models
-------------------------------------+-------------------------------------
     Reporter:  Jarek Glowacki       |                    Owner:  nobody
         Type:  New feature          |                   Status:  new
    Component:  Database layer       |                  Version:  master
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:
     Keywords:  bulk_create foreign  |             Triage Stage:
  key id                             |  Someday/Maybe
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------

Comment (by David Grant):

 My solution to this problem is the following:

 {{{
 class BulkHelperMixin:
     def bulk_create(self, objs, batch_size=None, ignore_conflicts=False):
         foreign_key_fields = [field for field in
 objs[0]._meta.get_fields() if type(field) == ForeignKey]
         for obj in objs:
             for foreign_key_field in foreign_key_fields:
                 parent_obj = getattr(obj, foreign_key_field.name)
                 if parent_obj and getattr(obj, foreign_key_field.column)
 is None:
                     setattr(obj, foreign_key_field.name, parent_obj)
         return super().bulk_create(objs, batch_size=batch_size,
 ignore_conflicts=ignore_conflicts)


 class BulkHelperManager(BulkHelperMixin, models.Manager):
     pass

 }}}

 Then in my model I do something like:

 {{{
     objects = models.Manager()
     bulk_manager = BulkHelperManager()
 }}}

 and then I just do bulk_create using my bulk_manager starting from the
 parent going down to the children. It works beautifully!

-- 
Ticket URL: <https://code.djangoproject.com/ticket/27408#comment:7>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/065.5930bcf7713b013710a7cee0c886cc52%40djangoproject.com.

Reply via email to