D
D
dr sbtn2016-04-20 17:43:07
Django
dr sbtn, 2016-04-20 17:43:07

How to correctly use foreign key in models?

am I using the foreign key correctly here? (the user will have one of the roles - admin, moderator, etc.)

class Role(models.Model):
    id_role = models.AutoField(primary_key=True)
    ...

class User(models.Model):
    id_user = models.AutoField(primary_key=True)
    ...
    id_role = models.ForeignKey(Role)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Viktor Melnikov, 2016-04-20
@dawasaturday

Right

A
Alexey Sergeev, 2016-04-20
@SergeevAI

id is not needed. Django ORM adds them automatically.
You can have many Users per Role, but each User can only have one Role.
If I understand correctly what you want, then you need models.ManyToManyField(Role)

A
Andrey Voskresensky, 2016-04-20
@Voskresenskyi

everything is correct in your example. only it is described in docks!!!! with examples...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question