0

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?

Mehdi Zare
  • 1,221
  • 1
  • 16
  • 32

2 Answers2

2

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/

Deac Karns
  • 1,191
  • 2
  • 13
  • 26
Marcelo Cardoso
  • 251
  • 3
  • 10
  • Thank you, Marcelo. It worked. Just a quick question, when do we use ManyToOneRel? – Mehdi Zare Feb 28 '19 at 15:29
  • I guess we would use ManyToOneRel if we want to change some inner functionality of Django. Take a look at this answer: https://stackoverflow.com/questions/15300422/difference-between-manytoonerel-and-foreignkey and the source code reference: https://github.com/django/django/blob/6d4e5feb79f7eabe8a0c7c4b87f25b1a7f87ca0b/django/db/models/fields/reverse_related.py – Marcelo Cardoso Feb 28 '19 at 15:36
1

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

phoibos
  • 3,900
  • 2
  • 26
  • 26