O
O
outsider_x2019-08-02 09:26:28
Django
outsider_x, 2019-08-02 09:26:28

How to create a slug in Django?

How to create a slug in Django?
I used SlugField and unique=True before . And in other examples I also saw this: Now I learned about the primary_key setting and I had a question, why not create a slug differently:
slug = models.SlugField(unique=True)

slug = models.SlugField(primay_key=True)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Sviridov, 2019-08-02
@outsider_x

It is possible, but if you need to implement an m2m connection (for example, if posts belong to several groups), then you will have to duplicate this slug in the link table. I don’t know how convenient this is, because the slug can change at all - and you will have to change it in several tables. Or, say, you need to store "likes" of posts in a separate table. In one case, you will have a post_id there, on which a foreign key will be assigned to the id (pk) field in the table with posts, and in the other you will have to register the slug again. From memory, if anything, varchar takes up more space than int, indexes for such columns, respectively, too.
Moreover, if you store the history of changes in the same table, then you will have to duplicate the slug. So primay_key=True would suddenly no longer work in this field.

A
Alexey Guest007, 2019-08-02
@Guest007

why not
is really the wrong question. It will be true
Why do I need it?

The documentation says that unique=True already creates an index. Primary_key has an autonumbered id (pk) field. An integer index is much more compact and faster than a string index, so it is preferable for pk. So don't create problems for yourself out of the blue.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question