mehdi
mehdi

Reputation: 1150

achieve to intended query set in django by ORM

I have below models:

class Post(models.Model):
    title = models.CharField(
        max_length=100,
        blank=True,
    )
    description = models.CharField(
        max_length=1500,
    )
    writer = models.ForeignKey(
        User,
        related_name='written_posts',
        related_query_name='written_post',
        null=True,
        on_delete=models.SET_NULL
    )
    klass = models.ForeignKey(
        'klass.Class',
        related_name='posts',
        related_query_name='published_post',
        on_delete=models.CASCADE
    )
    users = models.ManyToManyField(
        User,
        through='PostUser',
        related_name="posts",
        through_fields=('post', 'user'),
        blank=True,
    )

class PostUser(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post')
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user')
    student = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='student')

and now i want get list of posts that are belong to classes id=1 or id=2 and then have PostUser with user_id=3 and student_id=4. i try :

Post.objects.filter(klass_id__in=[1,2], users__user__in=[3], users__student__in=[4]).order_by('-create_date').distinct()

and another try:

qs = PostUser.objects.filter(post__klass_id__in=child.joined_classes_list, user_id=3, student_id=4).order_by('-id').distinct()
result = [obj.post for obj in qs]

but i can't achieve to goal and result is wrong,but without any error.thank you

Upvotes: 0

Views: 41

Answers (1)

vorujack
vorujack

Reputation: 1950

when you use through model then you can access through instance using related name not ManyToManyField related name. in your example you use __users points to User model then __user point to PostUser model. you can write expected query like this:

Post.objects.filter(
    klass_id__in=[1,2], 
    post__user__in=[3],
    post__student__in=[4]
).order_by('-create_date').distinct()

Upvotes: 1

Related Questions