Home > Blockchain >  Django: How to store certain objects of a model in another model
Django: How to store certain objects of a model in another model

Time:04-11

I am currently trying to create a user profile that will contain the courses that the user chose. Currently, the user profile model is UserProfile and the courses are objects of Course. I've tried using the ManyToMany field but that just results in UserProfile storing all courses in Course.

The two models are stored in different apps.

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default="default.jpg", upload_to="profile_pics")
    courses = models.ManyToManyField("course.Course", blank=True, default=None, related_name = "courses")


    def __str__(self):
        return f"{self.user.username} Profile"

Any help is appreciated. Thanks.

CodePudding user response:

You can create a new bridge table to connect the two models, for example:

class UserCourse(models.Model):
    user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    ...

Then, if you want to query all the courses that the user choose:

user_courses = UserCourse.objects.filter(user=login_user)
  • Related