Changes between Version 2 and Version 3 of Ticket #34884, comment 1


Ignore:
Timestamp:
Sep 29, 2023, 8:01:22 PM (14 months ago)
Author:
Laurent Lyaudet

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #34884, comment 1

    v2 v3  
    44`get_or_create_monkey_patch.py`
    55{{{
     6from django.core.exceptions import FieldDoesNotExist
    67from django.db.models import QuerySet, ForeignKey
    78
     
    1112
    1213def patched_get_or_create(self, defaults=None, **kwargs):
    13      result, created = original_get_or_create(self, defaults=defaults, **kwargs)
    14      if not created:
    15          for key, value in kwargs.items():
    16              if isinstance(result._meta.get_field(key), ForeignKey):
    17                  # isinstance handles OneToOneField also.
    18                  setattr(result, key, value)
    19      return result, created
     14    result, created = original_get_or_create(self, defaults=defaults, **kwargs)
     15    if not created:
     16        for key, value in kwargs.items():
     17            try:
     18                if isinstance(result._meta.get_field(key), ForeignKey):
     19                    # isinstance handles OneToOneField also.
     20                    setattr(result, key, value)
     21            except FieldDoesNotExist:
     22                pass
     23    return result, created
    2024
    2125
Back to Top