# How to automatically set the model field during the creation ?

**URL:** <https://forum.djangoproject.com/t/how-to-automatically-set-the-model-field-during-the-creation/3861>\
**Category:** Using Django\
**Created:** [August 12, 2020, 5:15pm UTC](https://forum.djangoproject.com/t/how-to-automatically-set-the-model-field-during-the-creation/3861 "2020-08-12T17:15:53Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![pitagora04](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pitagora04/32/1019_2.png) [@pitagora04](https://forum.djangoproject.com/u/pitagora04)\
**Post date:** [August 12, 2020, 5:15pm UTC](https://forum.djangoproject.com/t/how-to-automatically-set-the-model-field-during-the-creation/3861/1 "2020-08-12T17:15:53Z")

</div>

Simple use case which is for sure used a lot by all developers but I’m not sure how to approach it in Django ☹ (still learning the framework).  
Model has field `unique_id` which should be unique 4 hexa digits.  
Every time the new object is created, the `unique_id` should be automatically calculated and stored.

**How can I do this ?**

My idea was to have a function which is “bind” to `default` then disable this field on user-view so user cannot change it, but it seems my improvisation is not working ☹

```auto
class Product(models.Model):
    unique_id = models.CharField(max_length=4, default=generate_unique_id(), unique=True)
    # ... other code ...
    def generate_unique_id():
        # generate the code and then check if it's really unique among other model objects
        while True:
            u_id = uuid.uuid4().hex[:4].upper()
            if not Product.objects.filter(unique_id=u_id).exists():
                break
            return u_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:** [August 12, 2020, 5:20pm UTC](https://forum.djangoproject.com/t/how-to-automatically-set-the-model-field-during-the-creation/3861/2 "2020-08-12T17:20:10Z")

</div>

> [@pitagora04](#):
>
> `unique_id = models.CharField(max_length=4, default=generate_unique_id(), unique=True)`

The docs for the [default](https://docs.djangoproject.com/en/3.1/ref/models/fields/#default) parameter specifies that you want to supply a callable - in this case, the function name `generate_unique_id`. What you’re actually doing is calling the function, which returns your value and has assigned that one value as the default for all instances.  
What you want to do is remove the parens from after the function name.

Ken

---

<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:** [August 12, 2020, 5:22pm UTC](https://forum.djangoproject.com/t/how-to-automatically-set-the-model-field-during-the-creation/3861/3 "2020-08-12T17:22:54Z")

</div>

Note: 4 hex digits is a fairly small field - 65536 possible values. You may not have that many rows, but you will start seeing duplicate values being generated far earlier than that. (As a _very_ rough estimator, the square root of the range gives you an idea of how soon you would get a duplicate - in this case, 256. So you can expect to start seeing duplicate values being selected about half the time once you’ve got 256 rows.)

---

<div class="post-metadata">

**Author:** ![Suttonium](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/suttonium/32/1264_2.png) [@Suttonium](https://forum.djangoproject.com/u/Suttonium)\
**Post date:** [August 12, 2020, 5:27pm UTC](https://forum.djangoproject.com/t/how-to-automatically-set-the-model-field-during-the-creation/3861/4 "2020-08-12T17:27:35Z")

</div>

Side note, but, is there a reason you aren’t using UUIDField for your unique\_id?

---

<div class="post-metadata">

**Author:** ![pitagora04](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pitagora04/32/1019_2.png) [@pitagora04](https://forum.djangoproject.com/u/pitagora04)\
**Post date:** [August 13, 2020, 10:00am UTC](https://forum.djangoproject.com/t/how-to-automatically-set-the-model-field-during-the-creation/3861/5 "2020-08-13T10:00:45Z")

</div>

@KenWhitesell Thanks for you feedback, now I modified the code but something is still wrong - the column is not even created when running migrations (tried to delete and run migrations from scratch).

I guess this will not work as I want, is the problem that I want to run through all `Product.objects` in the function ?

```
def generate_unique_id():
    while True:
        u_id = uuid.uuid4().hex[:4].upper()
        if not Product.objects.filter(unique_id=u_id).exists():
            break
    return u_id
class Product(models.Model):
    unique_id = models.CharField(max_length=4, default=generate_unique_id, unique=True)
    # ... other fields ...
```

---

<div class="post-metadata">

**Author:** ![pitagora04](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pitagora04/32/1019_2.png) [@pitagora04](https://forum.djangoproject.com/u/pitagora04)\
**Post date:** [August 13, 2020, 10:24am UTC](https://forum.djangoproject.com/t/how-to-automatically-set-the-model-field-during-the-creation/3861/6 "2020-08-13T10:24:12Z")

</div>

Ok, I gave up - too much effort for such simple problem 🙂

So I decided to use id field as unique product number:

```auto
class Product(models.Model):
    # THIS IS NOT WORKING unique_id = models.CharField(max_length=4, default=generate_unique_id, unique=True)
    # WORKAROUND - use ID and add zeros before it when printing...
    def unique_id(self):
        return str(id).zfill(5)

```

---

<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:** [August 13, 2020, 12:25pm UTC](https://forum.djangoproject.com/t/how-to-automatically-set-the-model-field-during-the-creation/3861/7 "2020-08-13T12:25:02Z")

</div>

If the column isn’t created, you’ve got a different issue that would need to be addressed that is completely aside from the default parameter. But it sounds like you’ve moved on, so I won’t pursue that any further.
