# ValueError when creating models with a uuid as id

**URL:** <https://forum.djangoproject.com/t/valueerror-when-creating-models-with-a-uuid-as-id/36409>\
**Category:** Using the ORM\
**Created:** [November 14, 2024, 3:27pm UTC](https://forum.djangoproject.com/t/valueerror-when-creating-models-with-a-uuid-as-id/36409 "2024-11-14T15:27:45Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![makisegfault](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/makisegfault/32/24347_2.png) [@makisegfault](https://forum.djangoproject.com/u/makisegfault)\
**Post date:** [November 14, 2024, 3:27pm UTC](https://forum.djangoproject.com/t/valueerror-when-creating-models-with-a-uuid-as-id/36409/1 "2024-11-14T15:27:45Z")

</div>

| | |
| --- | --- |
| Django Version: | 5.1.1 |
| Python Version: | 3.12.6 |

I am trying to create and update some models with the ORM. When it reaches the save function, I get this error `Field 'id' expected a number but got 'Other'`

I think this is because my model uses a uuid for an id and a primary key, like this

```python
class GMod(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False
    )
    ...

```

My code to create the model does this when it is called. The `item` here is a dictionary that is automatically populated elsewhere, and a new `GMod` is only created like this under certain conditions.

```python
...
gmod = GMod(
    title = item['title_listing'],
    summary = item['overview'],
    genre_tags = item['g_tags'],
    ref_url = item['url'],
)
gmod.save()
...

```

Is there a good way to populate the `id` field when it is set to a uuid like this? I renamed `id` in the model to something else and ran into the same error.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 14, 2024, 3:37pm UTC](https://forum.djangoproject.com/t/valueerror-when-creating-models-with-a-uuid-as-id/36409/2 "2024-11-14T15:37:20Z")

</div>

Please post the complete traceback with the complete error, along with the view (or other function) that is executing when this error is thrown.

---

<div class="post-metadata">

**Author:** ![makisegfault](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/makisegfault/32/24347_2.png) [@makisegfault](https://forum.djangoproject.com/u/makisegfault)\
**Post date:** [November 14, 2024, 3:48pm UTC](https://forum.djangoproject.com/t/valueerror-when-creating-models-with-a-uuid-as-id/36409/3 "2024-11-14T15:48:47Z")

</div>

here is the relevant view

```python
class GDBUpdateView(LoginRequiredMixin, edit.FormView):
    form_class = UploadGDB
    template_name = 'db_update.html'
    success_url = reverse_lazy('g_list')

    def get(self, request):
        form = self.form_class()
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(request.POST, request.FILES)
        if form.is_valid():
            print("json submitted successfully!")
            parse_out_data_into_g(request.FILES['jdoc'])
            return redirect(success_url)
        else:
            return render(request, self.template_name, {'form': form})

    def form_valid(self, form):
        return super().form_valid(form)

def parse_out_data_into_g(json_file):
    data = json.load(json_file)
    for item in data:
        if not GMod.objects.filter(title=item['title_listing']):
            gmod = GMod(
                title = item['title_listing'],
                summary = item['overview'],
                genre_tags = item['game_tags'],
                ref_url = item['url'],
            )
            gmod.save()
        else:
            continue

```

and here is the trackback

```auto
Environment:

Request Method: POST
Request URL: http://localhost:8000/dbupdate/

Django Version: 5.1.1
Python Version: 3.12.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'games',
 'news',
 'reviews',
 'comm',
 'peeps',
 'apis',
 'rest_framework',
 'corsheaders',
 'martor',
 'compressor',
 'allauth_ui',
 'allauth',
 'allauth.account',
 'allauth.socialaccount',
 'widget_tweaks',
 'slippers',
 'crispy_forms',
 'crispy_tailwind',
 'tagulous',
 'imagekit']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'whitenoise.middleware.WhiteNoiseMiddleware',
 'corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'allauth.account.middleware.AccountMiddleware']

Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/django/db/models/fields/related_descriptors.py", line 239, in __get__
    rel_obj = self.field.get_cached_value(instance)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/fields/mixins.py", line 37, in get_cached_value
    return instance._state.fields_cache[self.cache_name]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

During handling of the above exception ('engine'), another exception occurred:
  File "/usr/local/lib/python3.12/site-packages/django/db/models/fields/ __init__.py", line 2123, in get_prep_value
    return int(value)
           ^^^^^^^^^^

The above exception (invalid literal for int() with base 10: 'Other') was the direct cause of the following exception:
  File "/usr/local/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/views/generic/base.py", line 104, in view
    return self.dispatch(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/contrib/auth/mixins.py", line 73, in dispatch
    return super().dispatch(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/views/generic/base.py", line 143, in dispatch
    return handler(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/games/views.py", line 72, in post
    parse_out_data_into_g(request.FILES['jdoc'])
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/games/views.py", line 102, in parse_out_data_into_g
    gmod.save()
    ^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/base.py", line 891, in save
    self.save_base(
    ^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/base.py", line 977, in save_base
    pre_save.send(
    ^
  File "/usr/local/lib/python3.12/site-packages/django/dispatch/dispatcher.py", line 189, in send
    response = receiver(signal=self, sender=sender, **named)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tagulous/signals/post.py", line 22, in __call__
    manager = descriptor.get_manager(instance)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tagulous/models/descriptors.py", line 91, in get_manager
    manager = SingleTagManager(self, instance)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tagulous/models/managers.py", line 46, in __init__
    self.tag_cache = self.get_actual()
                     ^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tagulous/models/managers.py", line 78, in get_actual
    value = self.descriptor.descriptor. __get__ (self.instance)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/fields/related_descriptors.py", line 257, in __get__
    rel_obj = self.get_object(instance)
              ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/fields/related_descriptors.py", line 220, in get_object
    return qs.get(self.field.get_reverse_related_filter(instance))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/query.py", line 635, in get
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
                                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/query.py", line 1476, in filter
    return self._filter_or_exclude(False, args, kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/query.py", line 1494, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/query.py", line 1501, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/sql/query.py", line 1609, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/sql/query.py", line 1641, in _add_q
    child_clause, needed_inner = self.build_filter(
                                 
  File "/usr/local/lib/python3.12/site-packages/django/db/models/sql/query.py", line 1468, in build_filter
    return self._add_q(
           
  File "/usr/local/lib/python3.12/site-packages/django/db/models/sql/query.py", line 1641, in _add_q
    child_clause, needed_inner = self.build_filter(
                                 
  File "/usr/local/lib/python3.12/site-packages/django/db/models/sql/query.py", line 1555, in build_filter
    condition = self.build_lookup(lookups, col, value)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/sql/query.py", line 1385, in build_lookup
    lookup = lookup_class(lhs, rhs)
             ^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/lookups.py", line 30, in __init__
    self.rhs = self.get_prep_lookup()
               ^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/lookups.py", line 369, in get_prep_lookup
    return super().get_prep_lookup()
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/lookups.py", line 88, in get_prep_lookup
    return self.lhs.output_field.get_prep_value(self.rhs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/models/fields/ __init__.py", line 2125, in get_prep_value
    raise e. __class__ (
    ^^^^^^^^

Exception Type: ValueError at /dbupdate/
Exception Value: Field 'id' expected a number but got 'Other'.

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 14, 2024, 3:58pm UTC](https://forum.djangoproject.com/t/valueerror-when-creating-models-with-a-uuid-as-id/36409/4 "2024-11-14T15:58:22Z")

</div>

Are any of those other fields being loaded a data type other than CharFields? (Specifically, are any of them any type of foreign key reference?)

Addendum: I am unable to recreate the symptoms you are describing from the information provided so far. Creating that basic object, assuming CharField for the other data elements works.

---

<div class="post-metadata">

**Author:** ![makisegfault](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/makisegfault/32/24347_2.png) [@makisegfault](https://forum.djangoproject.com/u/makisegfault)\
**Post date:** [November 14, 2024, 4:07pm UTC](https://forum.djangoproject.com/t/valueerror-when-creating-models-with-a-uuid-as-id/36409/5 "2024-11-14T16:07:53Z")

</div>

The `genre_tags` is a `ManyToManyField` and the `ref_url` is a URLField. There is a `ForeignKey` field in the model, by that is not created or updated here. Huh, I do have that `ForeignKey` field set to `default="Other"`

I removed that default and instead added `null=True, blank=True,` and the error is gone. Interesting.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 14, 2024, 4:11pm UTC](https://forum.djangoproject.com/t/valueerror-when-creating-models-with-a-uuid-as-id/36409/6 "2024-11-14T16:11:44Z")

</div>

> [@makisegfault](#):
>
> The `genre_tags` is a `ManyToManyField`

That’s not going to work as a direct assignment. (See the docs for [ManyToMany Relationships](https://docs.djangoproject.com/en/5.1/topics/db/examples/many_to_many/#many-to-many-relationships) for how to set them.)

> [@makisegfault](#):
>
> the `ref_url` is a URLField

You might want to put some error checking around that, too.

> [@makisegfault](#):
>
> Huh, I do have that `ForeignKey` field set to `default="Other"`

That would do it…

---

<div class="post-metadata">

**Author:** ![makisegfault](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/makisegfault/32/24347_2.png) [@makisegfault](https://forum.djangoproject.com/u/makisegfault)\
**Post date:** [November 14, 2024, 4:12pm UTC](https://forum.djangoproject.com/t/valueerror-when-creating-models-with-a-uuid-as-id/36409/7 "2024-11-14T16:12:55Z")

</div>

So even though that field wasn’t `id`, because it was a ForeignKey, the ORM treated it like an id?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 14, 2024, 4:59pm UTC](https://forum.djangoproject.com/t/valueerror-when-creating-models-with-a-uuid-as-id/36409/8 "2024-11-14T16:59:10Z")

</div>

A ForeignKey field in a model physically stores the primary key of the related table in the database. You have access to that key by using the `_id` suffix on the field name.

In other words, if you have:

```auto
    some_field = ForeignKey('SomeModel', ...)

```

Then `some_field` is a reference to an instance of `SomeModel`, while `some_field_id` _is_ the primary key of that instance.

See the docs for [ForeignKey](https://docs.djangoproject.com/en/5.1/ref/models/fields/#foreignkey) for more details.
