[Django] 1:N 관계, 최근 데이터만 함께 가져오기

658 단어 djangodjango
# 모델
class Product(models.Model):
	...
    
class Review(models.Model):
	product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, default=None)
    content = models.Textfield()
    ...

...

# 쿼리셋
def get_queryset(request):
        queryset = super().get_queryset(request)
        product_reviews = Review.objects.filter(
            product_id=OuterRef('pk'))
        latest_review = (
            product_reviews.order_by('-pk'))
        queryset = queryset.annotate(
            latest_review=Subquery(
                latest_review.values('content')[:1]), 
        )

        return queryset

좋은 웹페이지 즐겨찾기