shankarj67
shankarj67

Reputation: 1159

How to reference Users model to my app models and Provide a foreign key

I am using Django-Cookiecutter which uses Django-Allauth to handle all the authentication and there is one App installed called user which handles everything related to users like sign-up, sign-out etc.

I am sharing the models.py file for users

@python_2_unicode_compatible
class User(AbstractUser):

    # First Name and Last Name do not cover name patterns
    # around the globe.
    name = models.CharField(_('Name of User'), blank=True, max_length=255)

    def __str__(self):
        return self.username

    def get_absolute_url(self):
        return reverse('users:detail', kwargs={'username': self.username})

Now that I have added my new App say Course and my models.py is

class Course(models.Model):
    name = models.CharField(max_length=30)
    description = models.CharField(max_length=100)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("details:assess", kwargs={"id": self.id})

I have also defined my views.py as

@login_required
def course_list(request):
    queryset = queryset = Course.objects.all()
    print("query set value is", queryset)
    context = {
             "object_list" :queryset,
              }

return render(request, "course_details/Course_details.html", context)

Is there any way I can reference(Foreign key) User App to my Course App so that each user has their own Course assigned to it.

one of the possible ways is to filter objects on the basis of the user and pass it to the template

I can't figure it out that how to map users and course in order to get the list of course which is assigned to the particular user.

Upvotes: 0

Views: 368

Answers (2)

EarlyCoder
EarlyCoder

Reputation: 1313

Unless you are offering a course to just one user, it does not make sense to have a one-to-many relationship between User and Course models. So, you need a many-to-many relationship. It is also wise to extend the user model by creating a UserProfile model and relate UserProfile to your course. You can look here for how to extend the user model.

So, what you should really do is this:

class Course(models.Model):
    name = models.CharField(max_length=30)
    description = models.CharField(max_length=100)

    # Make sure you first import UserProfile model before referring to it
    students = models.ManyToManyField(UserProfile, related_name = 'courses')

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("details:assess", kwargs={"id": self.id})

Also, note that adding and querying many-to-many relationships are little different. Please see the docs for more detail.

Upvotes: 1

py-D
py-D

Reputation: 669

You can directly add foreign key as:

user = models.Foreignkey(User,related_name="zyz")

Upvotes: 0

Related Questions