Django models Field expected a number but got - Integer vs String return

I have following model setup

class Questionid(models.Model):
    qid = models.PositiveIntegerField(default=1, unique=True, validators=[MinValueValidator(1), MaxValueValidator(100000)])
    q_title = models.CharField(max_length=100)

    def __str__(self):
        return f"{self.qid}"

and

class Learningpath(models.Model):
    lpid = models.OneToOneField(Questionid, on_delete=models.SET_NULL, blank=True, null=True)
    learning_path_title = models.CharField(max_length=100)

   def save(self, *args , **kwargs):
        self.learning_path_title = str(Questionid.objects.get(qid=self.lpid).q_title)
        super(Learningpath, self).save(*args , **kwargs)
    
    def __str__(self):
        return self.learning_path_title

This gives me error Field ‘qid’ expected a number but got <Questionid: 10>.
any comments please?
If I return integer, it works fine but it does not show the qid values on admin…

Side note: When posting code (or templates, error messages, tracebacks, etc), enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted. Do not try to use the > characters to mark each line.

When requesting assistance with an error, please post the entire error message along with the traceback.

We’re likely also going to need to see the view that is involved with this.

@KenWhitesell thank you, it was my first post and I am also new to django. I have edited the code above. The error related to admin when I want to “add” and item. When I click on Save, I get below error:

TypeError at /admin/staticpages/learningpath/add/
Field 'qid' expected a number but got <Questionid: 10>.
Request Method:	POST
Request URL:	http://localhost:18080/admin/staticpages/learningpath/add/
Django Version:	4.2.3
Exception Type:	TypeError
Exception Value:	
Field 'qid' expected a number but got <Questionid: 10>.
Exception Location:	D:\00 VS Learning\FAIT\env\Lib\site-packages\django\db\models\fields\__init__.py, line 2055, in get_prep_value
Raised during:	django.contrib.admin.options.add_view
Python Executable:	D:\00 VS Learning\FAIT\env\Scripts\python.exe
Python Version:	3.11.4
Python Path:	
['D:\\00 VS Learning\\FAIT\\firstaitutor',
 'C:\\Users\\ahadr\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip',
 'C:\\Users\\ahadr\\AppData\\Local\\Programs\\Python\\Python311\\DLLs',
 'C:\\Users\\ahadr\\AppData\\Local\\Programs\\Python\\Python311\\Lib',
 'C:\\Users\\ahadr\\AppData\\Local\\Programs\\Python\\Python311',
 'D:\\00 VS Learning\\FAIT\\env',
 'D:\\00 VS Learning\\FAIT\\env\\Lib\\site-packages']

Traceback

Environment:


Request Method: POST
Request URL: http://localhost:18080/admin/staticpages/learningpath/add/

Django Version: 4.2.3
Python Version: 3.11.4
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'staticpages',
 'django_better_admin_arrayfield']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\db\models\fields\__init__.py", line 2053, in get_prep_value
    return int(value)
           ^^^^^^^^^^

The above exception (int() argument must be a string, a bytes-like object or a real number, not 'Questionid') was the direct cause of the following exception:
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\contrib\admin\options.py", line 688, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\utils\decorators.py", line 134, in _wrapper_view
    response = view_func(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\views\decorators\cache.py", line 62, in _wrapper_view_func
    response = view_func(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\contrib\admin\sites.py", line 242, in inner
    return view(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\contrib\admin\options.py", line 1886, in add_view
    return self.changeform_view(request, None, form_url, extra_context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\utils\decorators.py", line 46, in _wrapper
    return bound_method(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\utils\decorators.py", line 134, in _wrapper_view
    response = view_func(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\contrib\admin\options.py", line 1747, in changeform_view
    return self._changeform_view(request, object_id, form_url, extra_context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\contrib\admin\options.py", line 1798, in _changeform_view
    self.save_model(request, new_object, form, not add)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\contrib\admin\options.py", line 1227, in save_model
    obj.save()
    ^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\firstaitutor\staticpages\models.py", line 113, in save
    self.learning_path_title = str(Questionid.objects.get(qid=self.lpid).q_title)
                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\db\models\query.py", line 623, in get
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
                                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\db\models\query.py", line 1436, in filter
    return self._filter_or_exclude(False, args, kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\db\models\query.py", line 1454, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\db\models\query.py", line 1461, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\db\models\sql\query.py", line 1534, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\db\models\sql\query.py", line 1565, in _add_q
    child_clause, needed_inner = self.build_filter(
                                 
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\db\models\sql\query.py", line 1480, in build_filter
    condition = self.build_lookup(lookups, col, value)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\db\models\sql\query.py", line 1307, in build_lookup
    lookup = lookup_class(lhs, rhs)
             ^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\db\models\lookups.py", line 27, in __init__
    self.rhs = self.get_prep_lookup()
               ^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\db\models\lookups.py", line 341, in get_prep_lookup
    return super().get_prep_lookup()
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\db\models\lookups.py", line 85, in get_prep_lookup
    return self.lhs.output_field.get_prep_value(self.rhs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\00 VS Learning\FAIT\env\Lib\site-packages\django\db\models\fields\__init__.py", line 2055, in get_prep_value
    raise e.__class__(
    ^^^^^^^^

Exception Type: TypeError at /admin/staticpages/learningpath/add/
Exception Value: Field 'qid' expected a number but got <Questionid: 10>.

and my admin code

class LearningpathAdmin(admin.ModelAdmin, DynamicArrayMixin):
    model = Learningpath
    list_display = ("learning_path_title", "lpid",)
    list_filter = ("learning_path_title", "lpid",)
    fieldsets = (
        ('Learning Path Title and ID', {"fields": ("lpid", "learning_path_title")}),
    )
    
    add_fieldsets = (
        ('Learning Path Title and ID', {"fields": ("lpid", "learning_path_title")}),
    )
    search_fields = ("learning_path_title",)
    ordering = ("lpid",)

admin.site.register(Learningpath, LearningpathAdmin)

Because lpid is OneToOneField it needs an object not a number so Django through this error
Field 'qid' expected a number but got <Questionid: 10>.

Because qid is PositiveIntegerField so to get the id from OnToOneField
All you must do here is to use qid=self.lpid_id instead of qid=self.lpid

self.learning_path_title = str(Questionid.objects.get(qid=self.lpid_id).q_title)

Hope it helps

@cehceh Thank you so much, I was confused about where to look. Even though I was commenting out this code, I was still getting the same error.

Slight tweak to your suggestion and it is working just fine. I learned a few thing here.

self.learning_path_title = str(Questionid.objects.get(id=self.lpid_id).q_title)