Home > Net >  Did not create model for user table. is it mandatory for order table?
Did not create model for user table. is it mandatory for order table?

Time:05-19

I'm a newbie in django and doing my very first food delivery website. I've not created any model for user auth table but created model for my menu table. now i want to create a model for order table where i want to keep both menu id and user id as foreign key.. is it possible any way or i must create a model for user table also?

CodePudding user response:

django is already have a User model ready for you , you can use it as below:

#first import the user model
from django.contrib.auth.models import User

# then add it as a ForeignKey
class Order(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    menu = models.ForeignKey(Menu,on_delete=models.CASCADE)

CodePudding user response:

Hi and welcome to Stack OverFlow.

If you are starting a new project, it is better to inherit AbstractUser and use custom user model. This way it will be easier to customize your user model like adding fields, methods, customizing Django admin, etc.

Full reference here: https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project

For this you will have to create a custom user model and point AUTH_USER_MODEL to the model.

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass

Then in settings.py (Assuming user model is in user_app app:

AUTH_USER_MODEL="user_app.user"
  • Related