fiz
fiz

Reputation: 57

Django ForeignKey create

I want to assign many Region to the UserProfile model, how to do it?

the code

class Region(models.Model):
    name = models.CharField(max_length=30)
    created_at = models.DateTimeField(auto_now=True)

 class UserProfile(models.Model):

    user = models.OneToOneField(

    region = models.ForeignKey(Region, on_delete=models.CASCADE, null=True, blank=True)

Upvotes: 1

Views: 82

Answers (2)

Abhijith Konnayil
Abhijith Konnayil

Reputation: 4616

from django.contrib.auth.models import AbstractUser

class UserProfile(AbstractUser):
    regions = models.ManyToManyField(Region,related_name='User')

I think this is the ideal way to implement what you need. Using ManyToManyField allows you to map userprofile object to more than one region object and vice versa.

Also, Inheriting Abstract User allows you to add region field to Django User Table, which is better than creating another table for linking user to and region field.

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

The relation you describe is not a ForeignKey, which means that a UserProfile has (at most) one related Region, but a ManyToManyField [Django-doc].

A ManyToManyField thus means that a region can be related to zero, one, or more UserProfiles, and a UserProfile can be related to zero, one, or more Regions.

You can thus change the models to:

class Region(models.Model):
    name = models.CharField(max_length=30)
    created_at = models.DateTimeField(auto_now=True)

 class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    regions = models.ManyToManyField(Region)

In a relational database this is implemented by adding an extra (hidden) table with ForeignKeys to Regions and UserProfiles. But the Django ORM works in a "transparant" way and thus hides the implementation details.

See the documentation for more information on how to "populate" such relation.

Upvotes: 2

Related Questions