Django.fun

Manytomay field is None or can't call field in a view in django

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

Good day!

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: https://github.com/almazkun/django_to_many/blob/main/many/tests.py

Tutorials

Современный Python: начинаем проект с pyenv и poetry

Настройка проекта Python — виртуальные среды и управление пакетами

Использование requests в Python — тайм-ауты, повторы, хуки

Понимание декораторов в Python

ProcessPoolExecutor в Python: полное руководство

map() против submit() с ProcessPoolExecutor в Python

Понимание атрибутов, словарей и слотов в Python

Полное руководство по slice в Python

Выпуск Django 4.0

Безопасное развертывание приложения Django с помощью Gunicorn, Nginx и HTTPS

Автоматический повтор невыполненных задач Celery

Django REST Framework и Elasticsearch

Докеризация Django с помощью Postgres, Gunicorn и Nginx

Асинхронные задачи с Django и Celery

Релизы безопасности Django: 3.2.4, 3.1.12 и 2.2.24

Выпуски исправлений ошибок Django: 3.2.3, 3.1.11 и 2.2.23

Эффективное использование сериализаторов Django REST Framework

Выпуски безопасности Django: 3.2.2, 3.1.10 и 2.2.22

Выпущенные релизы безопасности Django: 3.2.1, 3.1.9 и 2.2.21

Обработка периодических задач в Django с помощью Celery и Docker

View all tutorials →