Mehdi Zare
Mehdi Zare

Reputation: 1381

ManyToOne relationship with User database

I want to create a model with a ManyToOne relationship with the user database.

Here's the code I used for the field:

from django.db import models
from django.contrib.auth.models import User

class user_extended(models.Model):
    user_ID = models.ManyToOneRel(User)

The migration doesn't work. It returns TypeError:

TypeError: init() missing 1 required positional argument: 'field_name'

How should I create a relationship with user database?

Upvotes: 0

Views: 231

Answers (2)

Marcelo Cardoso
Marcelo Cardoso

Reputation: 251

We define ManyToOne relationships on Django with a ForeingKey. So you should change

user_ID = models.ManyToOneRel(User)

to

user_ID = models.ForeignKey(User, on_delete=models.CASCADE)

Check out Django's documentation: https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_one/

Upvotes: 2

phoibos
phoibos

Reputation: 3979

If you want to have a ManytoOne relation (many user_extended to one User), you'd do it like this:

from django.db import models
from django.conf import settings

class user_extended(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

Note: the class name should be CamelCase, like this: UserExtended

Upvotes: 1

Related Questions