# How to add prefix to a unique id from another model?

**URL:** <https://forum.djangoproject.com/t/how-to-add-prefix-to-a-unique-id-from-another-model/5849>\
**Category:** Using Django\
**Created:** [December 25, 2020, 9:58am UTC](https://forum.djangoproject.com/t/how-to-add-prefix-to-a-unique-id-from-another-model/5849 "2020-12-25T09:58:33Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![sriram2107](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sriram2107/32/2673_2.png) [@sriram2107](https://forum.djangoproject.com/u/sriram2107)\
**Post date:** [December 25, 2020, 9:58am UTC](https://forum.djangoproject.com/t/how-to-add-prefix-to-a-unique-id-from-another-model/5849/1 "2020-12-25T09:58:33Z")

</div>

I created two models “Category” and “Item”. There is a field “title” in category model, I want the value of the “title field” to be prefix of my “unique id field” in Item module can anyone suggest me a solution for this problem.

Thank you

---

<div class="post-metadata">

**Author:** ![CodenameTim](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/codenametim/32/31507_2.png) [@CodenameTim](https://forum.djangoproject.com/u/CodenameTim)\
**Post date:** [December 25, 2020, 1:14pm UTC](https://forum.djangoproject.com/t/how-to-add-prefix-to-a-unique-id-from-another-model/5849/2 "2020-12-25T13:14:35Z")

</div>

You could create a property on the `Item` model:

```auto
class Item(models.Model):
    title = models.CharField()

    @property
    def some_other_field(self):
        # Combines title and the auto generated id
        return f"{self.title}_{self.id}"

```

[Check out the docs about it here](https://docs.djangoproject.com/en/3.1/topics/db/models/#model-methods)

---

<div class="post-metadata">

**Author:** ![sriram2107](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sriram2107/32/2673_2.png) [@sriram2107](https://forum.djangoproject.com/u/sriram2107)\
**Post date:** [December 25, 2020, 1:30pm UTC](https://forum.djangoproject.com/t/how-to-add-prefix-to-a-unique-id-from-another-model/5849/3 "2020-12-25T13:30:50Z")

</div>

can i use the value of title as prefix in Item model  
“`class Category(models.Model): title = models.CharField()`” in another model `class Item(models.Model):product_id=title(from category)+uniqueid`.,  
To be more precise i want a unique id as such  
for example "the vale of title in category module is= BOOK " and the unique id at Item module is 00000123.I want BOOK as prefix of my unique id and the id should increment as i add a item of same category, and should change if it is different category.  
I hope I elaborately explained my problem can you please help me with it.

Thank you

---

<div class="post-metadata">

**Author:** ![CodenameTim](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/codenametim/32/31507_2.png) [@CodenameTim](https://forum.djangoproject.com/u/CodenameTim)\
**Post date:** [December 25, 2020, 1:57pm UTC](https://forum.djangoproject.com/t/how-to-add-prefix-to-a-unique-id-from-another-model/5849/4 "2020-12-25T13:57:07Z")

</div>

What you’re looking for is possible. Take a look at the [example of foreign keys](https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_one/). It’ll show you how to traverse model relationships. You can combine that with the property method above to accomplish it.

The requirement of having a counter for each individual category is a bit more difficult. You’ll want to make use of [UniqueConstraint](https://docs.djangoproject.com/en/3.1/ref/models/constraints/#django.db.models.UniqueConstraint).

```
class Item(models.Model):
    category = models.ForeignKey(Category)
    index = models.IntegerField()

    class Meta:
        constraints = [UniqueConstraint(fields=['category', 'index'], name='unique_category_id'))
```

---

<div class="post-metadata">

**Author:** ![sriram2107](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sriram2107/32/2673_2.png) [@sriram2107](https://forum.djangoproject.com/u/sriram2107)\
**Post date:** [December 26, 2020, 5:30am UTC](https://forum.djangoproject.com/t/how-to-add-prefix-to-a-unique-id-from-another-model/5849/5 "2020-12-26T05:30:56Z")

</div>

Thank you for your response I will try this and let you know if it works

---

<div class="post-metadata">

**Author:** ![sriram2107](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sriram2107/32/2673_2.png) [@sriram2107](https://forum.djangoproject.com/u/sriram2107)\
**Post date:** [December 28, 2020, 11:50am UTC](https://forum.djangoproject.com/t/how-to-add-prefix-to-a-unique-id-from-another-model/5849/6 "2020-12-28T11:50:22Z")

</div>

As per the above solution you suggested me I am able to generate an unique id but can’t get prefix as per requirement. So can you please elaborate the above solution  
Thank you

---

<div class="post-metadata">

**Author:** ![CodenameTim](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/codenametim/32/31507_2.png) [@CodenameTim](https://forum.djangoproject.com/u/CodenameTim)\
**Post date:** [December 28, 2020, 3:00pm UTC](https://forum.djangoproject.com/t/how-to-add-prefix-to-a-unique-id-from-another-model/5849/7 "2020-12-28T15:00:03Z")

</div>

Looks like I missed returning the title from the category field.

```auto
class Item(models.Model):
    @property
    def some_other_field(self):
        # Combines the category's title and the auto generated id
        return f"{self.category.title}_{self.id}"

```

---

<div class="post-metadata">

**Author:** ![sriram2107](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sriram2107/32/2673_2.png) [@sriram2107](https://forum.djangoproject.com/u/sriram2107)\
**Post date:** [December 29, 2020, 6:24am UTC](https://forum.djangoproject.com/t/how-to-add-prefix-to-a-unique-id-from-another-model/5849/8 "2020-12-29T06:24:09Z")

</div>

Sorry for the late response, I will try it and let you know if it works  
Thank you.

---

<div class="post-metadata">

**Author:** ![sriram2107](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sriram2107/32/2673_2.png) [@sriram2107](https://forum.djangoproject.com/u/sriram2107)\
**Post date:** [January 4, 2021, 11:18am UTC](https://forum.djangoproject.com/t/how-to-add-prefix-to-a-unique-id-from-another-model/5849/9 "2021-01-04T11:18:52Z")

</div>

Hi Sir, Regarding the same issue  
This is my Category model  
`class Category(models.Model):`

`cat_title = models.CharField(max_length=100, unique=True)`

This is my Item model

```
class Item(models.Model):

```

`product_id = models.CharField(primary_key=True, editable=False, max_length=100)`  
`prefix = models.OneToOneField(Category, to_field='cat_title', related_name='prefix', on_delete=models.CASCADE)`

```
    def save(self, **kwargs):
        if not self.product_id:
            max = Item.objects.aggregate(id_max=Max('product_id'))['id_max']
            self.product_id = "{}{:10}".format(self.prefix, max if max is not None else 1)
        super().save(*kwargs)``

```

here i am using a **foreign key as prefix to my unique id** , My issue here is that i can not add multiple items to my **Item Module**  
as the prefix is showing unique, **If I remove unique=True from Category module** the code is not running so i think incrementing prefix with certain value in Item Module might resolve my issue, Can you please help me with this issue

---

<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:** [January 4, 2021, 12:50pm UTC](https://forum.djangoproject.com/t/how-to-add-prefix-to-a-unique-id-from-another-model/5849/10 "2021-01-04T12:50:21Z")

</div>

As a side note - When you post code, to prevent the formatting being lost, enclose the code between two lines consisting only of three backtick ` characters. So you would have a line of ```, then your lines of code, then another line ```. (Make sure you use the backtick - ` and not the apostrophe ’ ) The single-backtick method only works on one line.

---

<div class="post-metadata">

**Author:** ![sriram2107](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sriram2107/32/2673_2.png) [@sriram2107](https://forum.djangoproject.com/u/sriram2107)\
**Post date:** [January 4, 2021, 12:52pm UTC](https://forum.djangoproject.com/t/how-to-add-prefix-to-a-unique-id-from-another-model/5849/11 "2021-01-04T12:52:24Z")

</div>

Ok Sure, I will follow your instructions while posting code.  
Thank you

---

<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:** [January 4, 2021, 1:09pm UTC](https://forum.djangoproject.com/t/how-to-add-prefix-to-a-unique-id-from-another-model/5849/12 "2021-01-04T13:09:43Z")

</div>

You’re getting closer - but it’s just one set of three backticks before and after all the lines. Example:

````auto
# The line before this one is ```
def function(self):
    return self
# The line after this one is ```

````

See how that’s formatted?

Now, to address the issue you’ve identified here. You’ve got:

```
        max = Item.objects.aggregate(id_max=Max('product_id'))['id_max']

```

the field `product_id` is a character field, it’s going to hold the max value of that field. (Note: you probably don’t want to use a field named “max” - it’s the name of a built-in python function.)

Then you have:

```
        self.product_id = "{}{:10}".format(self.prefix, max if max is not None else 1)

```

This is going to set `self.product_id` to the **same** value that you just found in the previous statement, which is why you’re getting the error you’re seeing.

If you need to track the highest number for each `Category`, what you probably want to do is add an autoincrement field to your `Category` rather than querying the entire table for the highest number used - that’s going to become increasingly inefficient as the number of rows in your table increases - and subject to race conditions.
