Skip to content

ForeignKeyWidget: add get_lookup_kwargs() #1651

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ Please refer to :doc:`release notes<release_notes>`.
4.0.0-alpha.6 (unreleased)
--------------------------

- added :meth:`~import_export.widgets.ForeignKeyWidget.get_lookup_kwargs` to make it easier to override object
lookup (#1651)
- removed unused variable ``Result.new_record`` (#1640)
- Refactor ``resources.py`` to standardise method args (#1641)
- added specific check for missing ``import_id_fields`` (#1645)
Expand Down
33 changes: 30 additions & 3 deletions import_export/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,8 +422,12 @@ def get_queryset(self, value, row, *args, **kwargs):
Overwrite this method if you want to limit the pool of objects from
which the related object is retrieved.

:param value: The field's value in the datasource.
:param row: The datasource's current row.
:param value: The field's value in the dataset.
:param row: The dataset's current row.
:param \\*args:
Optional args.
:param \\**kwargs:
Optional kwargs.

As an example; if you'd like to have ForeignKeyWidget look up a Person
by their pre- **and** lastname column, you could subclass the widget
Expand All @@ -439,17 +443,40 @@ def get_queryset(self, value, row, *args, **kwargs):
return self.model.objects.all()

def clean(self, value, row=None, **kwargs):
"""
Return a single Foreign Key instance derived from the args.
``None`` can be returned if the value passed is a null value.

:param value: The field's value in the dataset.
:param row: The dataset's current row.
:param \\**kwargs:
Optional kwargs.
:raises: ``ObjectDoesNotExist`` if no valid instance can be found.
"""
val = super().clean(value)
if val:
if self.use_natural_foreign_keys:
# natural keys will always be a tuple, which ends up as a json list.
value = json.loads(value)
return self.model.objects.get_by_natural_key(*value)
else:
return self.get_queryset(value, row, **kwargs).get(**{self.field: val})
lookup_kwargs = self.get_lookup_kwargs(value, row, **kwargs)
return self.get_queryset(value, row, **kwargs).get(**lookup_kwargs)
else:
return None

def get_lookup_kwargs(self, value, row, **kwargs):
"""
Returns the key value pairs used to identify a model instance.
Override this to customize instance look up.

:param value: The field's value in the dataset.
:param row: The dataset's current row.
:param \\**kwargs:
Optional kwargs.
"""
return {self.field: value}

def render(self, value, obj=None):
if value is None:
return ""
Expand Down
18 changes: 18 additions & 0 deletions tests/core/migrations/0013_alter_author_birthday.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.2.3 on 2023-10-11 03:54

import django.utils.timezone
from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("core", "0012_delete_legacybook"),
]

operations = [
migrations.AlterField(
model_name="author",
name="birthday",
field=models.DateTimeField(default=django.utils.timezone.now),
),
]
3 changes: 2 additions & 1 deletion tests/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone


class AuthorManager(models.Manager):
Expand All @@ -24,7 +25,7 @@ class Author(models.Model):
objects = AuthorManager()

name = models.CharField(max_length=100)
birthday = models.DateTimeField(auto_now_add=True)
birthday = models.DateTimeField(default=timezone.now)

def natural_key(self):
"""
Expand Down
13 changes: 13 additions & 0 deletions tests/core/tests/test_widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,19 @@ def get_queryset(self, value, row):
with self.assertRaises(TypeError):
birthday_widget.clean("Foo", row=row_dict, row_number=1)

def test_lookup_multiple_columns(self):
# issue 1516 - override the values used to lookup an entry
class BirthdayWidget(widgets.ForeignKeyWidget):
def get_lookup_kwargs(self, value, row, *args, **kwargs):
return {"name": row["name"], "birthday": row["birthday"]}

target_author = Author.objects.create(name="James Joyce", birthday="1882-02-02")
row_dict = {"name": "James Joyce", "birthday": "1882-02-02"}
birthday_widget = BirthdayWidget(Author, "name")
# prove that the overridden kwargs identify a row
res = birthday_widget.clean("non-existent name", row=row_dict)
self.assertEqual(target_author, res)

def test_render_handles_value_error(self):
class TestObj(object):
@property
Expand Down