1

I am creating an enrolment page for a website using Django. I have three tables: the default User table, a Profile table (to capture additional info) and a Subscription table.

I have setup the Profile table as follows:

class Profile(models.Model): 
    user_id = models.ForeignKey(User, on_delete=models.CASCADE)
    profile_id = models.AutoField(primary_key=True)

I have setup the Subscription table as follows:

class Subscription(models.Model):
   subscription_no = models.AutoField(primary_key=True)
   user_id = models.ForeignKey(User, on_delete=models.CASCADE)
   profile_id = models.ForeignKey(Profile, on_delete=models.CASCADE)

When a new user enrols, I create a new Profile and Subscription object for that user in views.py:

 #Create a new Profile object for the User
 user_profile = Profile()
 lookup_user = User.objects.get(username=username)
 lookup_user_id = lookup_user.pk
 user_profile.user_id = User.objects.get(pk=lookup_user_id)

 #Create a new Subscription object for the User
 user_subscription = Subscription()
 user_subscription.user_id = User.objects.get(pk=lookup_user_id) 

 lookup_profile = Profile.objects.get(user_id=user_profile.user_id)
 lookup_profile_id = lookup_profile.pk
 user_subscription.profile_id = Profile.objects.get(pk=lookup_profile_id)

Everything works okay, except I am worried that I am establishing the relationship between the tables in an incorrect manner. When I add the User, Profile and Subscription tables to the Django Admin app, the following appears for each new user profile:

New Profile for a created user

The following appears for a Subscription object created for a new User:

New Subscription created for a user

And finally, if I open up a Subscription object, for example, the relationship field (which should be the primary key) just displays the text "Profile object":

Relationship field between User Profile and User Subscription

I thought that the profile_id field would be an auto-increment number that would appear instead of "Profile object". I am new to Django, and I am worried that I am not establishing the relationship between the Tables correctly.

Your advice is much appreciated. Thanks in advance.

Sean
  • 586
  • 5
  • 8

1 Answers1

3

You are correct autoincrement id field will be used as foreign key. As for django admin subscription object is just defaul representation string of instance you can change it by adding __str__ method to your models like this:

class Profile(models.Model): 
    user_id = models.ForeignKey(User, on_delete=models.CASCADE)
    profile_id = models.AutoField(primary_key=True)

    def __str__(self):
        return str(self.profile_id)

With this you will see profile's id instead of profile object.

neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100