mr.abdo
mr.abdo

Reputation: 485

How to get multiple values from joined tables

How can I get all the laws from all the courses that an specific user is subscribed?

class Law(models.Model):
    name  = models.CharField('Nome', max_length=100)
    slug = models.SlugField('Atalho')
    description = models.TextField('Description', blank = True, null=True)

class Course(models.Model):
    name  = models.CharField('Nome', max_length=100)
    slug = models.SlugField('Atalho')
    description = models.TextField('Descrição', blank = True, null=True)
    laws = models.ManyToManyField(Law, related_name='law_course')


class Subscription(models.Model):    
    STATUS_CHOICES=(
        (
            (0, 'Pendente'),
            (1, 'Approved'),
            (2, 'Canceled'),
        )
    )
    user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, verbose_name="Usuário", related_name="inscricao") #inscricao é criado no usuario
    course = models.ForeignKey(Course, on_delete=models.CASCADE, verbose_name="Course", related_name="subscription")
    status = models.IntegerField(
        'Status', choices=STATUS_CHOICES, default = 0, blank=True
        )

    class Meta:
        unique_together = (('user','course'))

So, the user can be subscribed in one or more courses. Each course has one or many laws.

I have a page that I need to list all the laws of each course that an specific user is subscribed if the subscription is Approved (status = 1). Example: The user John has subscribed in 2 courses: Course A and Course B.

Course A laws: law1, law2, law3
Course B laws: law1, law20, law30

So, when John is logged in, I need to show the laws of the courses and the name of the course:

law1 - Course A, Course B
law2 - Course A
law3 - Course A
law20 - Course B
law30 - Course B

Note that I can't show law 1 twice, but I showed each course that contains this law.

I did my best to be clear. Tks in advance

Upvotes: 0

Views: 62

Answers (1)

Vipin Gupta
Vipin Gupta

Reputation: 890

You can use a set to store the laws (which will eventually be unique).

laws_set = set()
subscriptions = Subscription.objects.filter(user=your_user, status=1)

For each subscription, get the course and then get all the laws corresponding to that course.

for subscription in subscriptions:
    laws = subscription.course.laws.all() 

    for law in laws:
        laws_set.add(law)

Now for each law in the laws_set, you can print the corresponding courses.

for law in laws_set:
    print(law.name, end='')
    for course in law.law_course.all(): # Since law_course is the related name
        print(course.name, end='')
    print('\n')

Upvotes: 3

Related Questions