A field already has access to the other foreign key in a table

Viewed 39
class User(models.Model):
     ...


class Phone(models.Model):
    user = models.OneToOneField(User)
    phone = models.TextField()

class profile(models.Model):
    user = models.OneToOneField(User)
    user_phone = models.OneToOneField(Phone)

Already user field in profile has access to phone, So is this design ok or bad based on a normalization view?

1 Answers

The modeling is quite strange. Your Phone model has a ForeignKey to the User model. Furthermore your Profile seems to act as a junction-table between User and Phone.

Since you made a custom user model, there is no need for a Profile model, and definitely not one with a relation to the Phone model.

You can simply extend your User model with extra fields that you want to store (that are now in the Profile model), and then make use of a ForeignKey from Phone to user to specify that that phone (there can be zero, one or multiple) belongs to that user, so something like:

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    # …
    # fields for the user and 
    # extra data that was stored in
    # the Profile model


class Phone(models.Model):
    phone = models.TextField()
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='phones'
    )
Related