如何将命名参数传递给另一个函数需要的函数?

时间:2017-08-04 19:14:01

标签: python django

编辑:我已经改变了标题,以更好地代表我寻求的解决方案。

我重复了一段代码,想写一个函数来减少混乱。我在传递kwarg键hourly_id时遇到了问题(原始代码的最后一行)。

原始代码

# 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

新功能

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 

功能调用

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

所以你可以在这里看到我正在尝试使用字符串将hourly_id作为id传递,但是我收到数据库错误,说明hourly_id已丢失,所以我在显然没有正确传递它。

回溯

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

1 个答案:

答案 0 :(得分:1)

这是我发现问题的地方:

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

您可以根据需要将变量重命名为更通用,但hourly_id不是变量,而是命名参数。通过使用id,您不会传入预期的hourly_id参数,而是传入可能不需要的或不正确的id参数。

除非您更改create()本身的定义,否则参数名称仍为hourly_id。解决这个问题的一种方法是在可能的情况下使用参数,而不是按名称。 (即,它是仅关键字参数还是由关键字访问的位置参数?)

或者,如果您将'hourly_id'作为id传递,则使用此键和值增加point_data

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})