简体   繁体   中英

How do you pass a named parameter into a function that another function needs?

EDIT: I've changed the title to better represent the solution I seeking.

I'm repeating a block of code and would like to a write a function to reduce clutter. I'm having trouble passing in the kwarg key hourly_id (last line of the original code).

Original Code

# Create Hourly data.
hourly_data = validated_data.pop('hourly')
hourly_points_data = hourly_data.pop('data')
hourly = Hourly.objects.create(**hourly_data)
for hourly_point_data in hourly_points_data:
    hourly_point = HourlyPoint.objects.create(
        hourly_id=hourly.pk, **hourly_point_data)    <-- This

New Function

def create_data_block(self, data, block_str, DataBlock, DataPoint, id):
    block_data = data.pop(block_str)
    points_data = block_data.pop('data')
    block = DataBlock.objects.create(**block_data)
    for point_data in points_data:
        point = DataPoint.objects.create(
            id=block.pk, **point_data)    <-- This 

Function Call

self.create_data_block(validated_data, 'hourly', Hourly, HourlyPoint, 'hourly_id')

So you can see here I am trying to pass hourly_id as id using a string, but I get a database error saying that that hourly_id was missing so I'm clearly not passing it in correctly.

Traceback

Traceback (most recent call last):
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/lib/python3.5/contextlib.py", line 30, in inner
    return func(*args, **kwds)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/rest_framework/views.py", line 489, in dispatch
    response = self.handle_exception(exc)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/rest_framework/views.py", line 449, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/rest_framework/views.py", line 486, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/cudb/Projects/a/b/c/weather/views.py", line 36, in get
    response = self.get_entry(latitude, longitude)
  File "/home/cudb/Projects/a/b/c/weather/views.py", line 59, in get_entry
    response = self.create_or_update_entry(latitude, longitude)
  File "/home/cudb/Projects/a/b/c/weather/views.py", line 76, in create_or_update_entry
    location_serializer.save()
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/rest_framework/serializers.py", line 215, in save
    self.instance = self.create(validated_data)
  File "/home/cudb/Projects/a/b/c/weather/serializers.py", line 119, in create
    validated_data, 'hourly', Hourly, HourlyPoint, 'hourly_id')
  File "/home/cudb/Projects/a/b/c/weather/serializers.py", line 169, in create_data_block
    id=block.pk, **point_data)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/query.py", line 399, in create
    obj.save(force_insert=True, using=self.db)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/base.py", line 796, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/base.py", line 824, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/base.py", line 908, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/base.py", line 947, in _do_insert
    using=using, raw=raw)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/query.py", line 1045, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql
    cursor.execute(sql, params)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/debug_toolbar/panels/sql/tracking.py", line 164, in execute
    return self._record(self.cursor.execute, sql, params)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/debug_toolbar/panels/sql/tracking.py", line 106, in _record
    return method(sql, params)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: null value in column "hourly_id" violates not-null constraint
DETAIL:  Failing row contains (6, 76.22, 77.31, 0.80, 0.00, clear-night, Clear, null).

[04/Aug/2017 12:05:30] "GET /weather/0,4 HTTP/1.1" 500 288106

This where I see a problem:

hourly_point = HourlyPoint.objects.create(hourly_id=hourly.pk, **hourly_point_data)
point = DataPoint.objects.create(id=block.pk, **point_data)

You can rename the variables to be more generic as you see fit, but hourly_id is not a variable, it's a named parameter. By using id instead, you're not passing in the expected hourly_id argument but passing in a potentially unwanted, or incorrect, id argument.

Unless you change the definition of create() itself, the argument name remains hourly_id . One way around this is to use the argument positionally, if possible, instead of by name. (Ie is it a keyword argument only or a positional argument being accessed by keyword?)

Alternatively, if you pass in 'hourly_id' as id then augment point_data with this key and value:

def create_data_block(self, data, block_str, DataBlock, DataPoint, id):
    block_data = data.pop(block_str)
    points_data = block_data.pop('data')
    block = DataBlock.objects.create(**block_data)
    for point_data in points_data:
        point = DataPoint.objects.create(**{id: block.pk, **point_data})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM