Home>

I want to store the data acquired on the server side with django in the database, but I get an error saying ValueError: Field'id' expected a number but got'suzukitadashi'.

In models.py in the app project

from django.db import models
from django.contrib.auth.models import User

class User (models.Model):
    user_id = models.CharField (max_length = 10)
    password1 = models.CharField (max_length = 20)
    password2 = models.CharField (max_length = 20)

class Analytics (models.Model):
    user_foreign_key = models.ForeignKey ("auth.User", on_delete = models.CASCADE, verbose_name = "foreign_key")
    point = models.CharField (max_length = 200)


Write
In models.py in the index project

from django.db import models
class UserData (models.Model):
    data_foreign_key = models.ForeignKey ("registration.User", on_delete = models.CASCADE)
    user_id = models.CharField (max_length = 20)
    access_date = models.DateTimeField ('access date and time')


I wrote.
index views.py

def top (request):
    json_data = json.loads (request.body.decode ("utf-8"), strict = False)
    user_data = UserData.objects.get (data_foreign_key = "suzukitadashi")
    user_data.user_id = get_random_string (10)
    user_data.access_date = datetime.datetime.now ()
    user_data.save ()
    return JsonResponse (json_data, safe = False)


I wrote.

When I accessed this top method and executed the data storage code, I got the above error.
As a test

user_data = UserData.objects.get (data_foreign_key = 1)


I got an error even if I rewrote it.

I'm logged in to the django app with suzukitadashi.
What is the error causing the problem? ??

  • Answer # 1

    I'm sorry. I didn't know where to fix it, so I corrected it.

    "Value Error: Cannot query" suzukitadashi ": Must be" User "instance." Indicates that "" suzukitadashi "cannot be queried, so it must be a" User "instance".

    def top (request):
        json_data = json.loads (request.body.decode ("utf-8"), strict = False)
        # user_data = UserData.objects.get (data_foreign_key = "suzukitadashi")
        user = User.objects.get (user_id ='suzukitadashi')
        user_data = UserData.objects.get (data_foreign_key = user)
        user_data.user_id = get_random_string (10)
        user_data.access_date = datetime.datetime.now ()
        user_data.save ()
        return JsonResponse (json_data, safe = False)