Home > Software engineering >  Manytomay field is None or can't call field in a view in django
Manytomay field is None or can't call field in a view in django

Time:06-08

I have a problem in my code,I'm Trying to querying to my course model, I have a many to may field of course in user model,now I need to query to course model that course title or id is equal to user's courses

My course model is:


    class Courses(models.Model):
    title = models.CharField(max_length=100, null=False, blank=False)
    description = models.TextField(null=False, blank=False)
    active = models.BooleanField(default=False)
    default_course = models.BooleanField(default=False)

My user model in another app is:


    class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255, unique=True, db_index=True)
    courses = models.ManyToManyField('academy.Courses', related_name='user_courses', 
     blank=True)
    is_verified = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_author = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)
    is_adviser = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    auth_provider = models.CharField(
        max_length=255, blank=False,
        null=False, default=AUTH_PROVIDERS.get('email'))

I have to say my user model and course model are in different app

This is my view:


    class CoursesListView(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = UserSerializer

    def get_queryset(self, **kwargs):
        user = self.request.user
        course = Courses.objects.filter(title__in=user.courses.title)

I tried so many code but none of them worked,please any one can help me how can I write this view?

as I said I want to call courses that have same id or title with user courses

CodePudding user response:

If you want to show all Courses of this user, change your code:

    def get_queryset(self, **kwargs):
        user = self.request.user
        course = Courses.objects.filter(user_courses=user) # <- this
        # or
        course = user.courses.all() # <- this

Also, be sure to add Many to many object properly:

course_data = {'title': 'Django', 'description': 'Django course', 'active': True, 'default_course': True}
course = Courses.objects.create(**course_data)
user = MyUser.objects.create_user(username='test', password='test')
user.courses.add(course) # <- this

Can take a look at this file:

  • Related