Samuel
Samuel

Reputation: 37

Django referencing foreignkeys on updates

I asked this question before, it got closed because I didn't provide sufficient information to the situation. This is the edit.

I'm running Django and running into this problem. I'm trying to create or update an entry in my MySQL table. One of the keys is, however, a foreignKey. (I know how to create table entries with foreignKeys, but my approach doesn't work) As per Django reference for doing the recommended way is to set the new table entry as default value.

Which I did:

item = {}
for entry in params:
    if entry not in ['_state', 'timestamp', 'rule_case', 'session_key']:
        item[entry] = params[entry]

        if entry == 'code':
            item[entry] = Demo_user_sessions.objects.get(session=session_key)

obj, created = Demo_user_sessions.objects.update_or_create(session=session_key, defaults=item)

This I extended by looking for the special key and replacing the content with the link to the referenced table. The one by the foreignKey.

Here my model for the entry that I am trying to make.

class Demo_user_sessions(models.Model):
    session_key = models.CharField(primary_key=True, max_length=8)
    timestamp = models.DateTimeField(auto_now_add=True)
    code = models.ForeignKey('HS_Code', on_delete=models.CASCADE, null=True)
    # ... some other

    class Meta:
        ordering = ['timestamp']

    def __str__(self):
        return self

Here my current error message when doing:

Traceback (most recent call last):
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
    raise exc
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler
    return func(*args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/Mantaray/main/views.py", line 111, in api_user_session
    obj, created = Demo_user_sessions.objects.update_or_create(session=params['session_key'], defaults=item)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/query.py", line 584, in update_or_create
    setattr(obj, k, v() if callable(v) else v)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 215, in __set__
    'Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/base.py", line 518, in __repr__
    return '<%s: %s>' % (self.__class__.__name__, self)
TypeError: __str__ returned non-string (type Demo_user_sessions)

I kinda get the problem of the error message. I just don't know what to change or what to do differently.

Upvotes: 0

Views: 51

Answers (2)

m0dknight
m0dknight

Reputation: 169

Update your model from

code = models.ForeignKey('HS_Code', on_delete=models.CASCADE, null=True)

to

code = models.ForeignKey(HS_Code, on_delete=models.CASCADE, null=True)

Upvotes: 1

schillingt
schillingt

Reputation: 13731

So there are two issues, 1) __str__ must return a string representation of the instance. 2) item["code"] must be an instance of HS_Code or you could do item["code_id"] = some_integer_id_representing_the_HS_Code.

So something like:

def __str__(self):
    return self.session_key

And:

if entry == 'code':
    item[entry] = HS_Code.objects.get(some_lookup=some_value)

Upvotes: 1

Related Questions