Home > OS >  How to get those records which have a foreign key connected with another exact foreign key?
How to get those records which have a foreign key connected with another exact foreign key?

Time:07-18

I build API with django & django rest framework and stuck with writing one view. See the code below:

models.py

class Order(models.Model):
    name = models.CharField(max_length=255) 
    posted_by = models.ForeignKey(User, on_delete=models.CASCADE)

class Offer(models.Model): 


    order_related = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='offers')
    author = models.ForeignKey(User, on_delete=models.CASCADE)

serializers.py:

class OfferSerializer(serializers.ModelSerializer):
    class Meta:
        model = Offer
        fields = '__all__'

class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = '__all__'

Now I need a view which return those orders, which have offers in which author = int:pk. E.g.

GET /orders/3

should give all orders which have offers with author = 3

plz help me - I can write it with raw SQL but have no idea how to do it via ORM

CodePudding user response:

In this case you can simply use pre_fecthes using select_related

offer = Offer.objects.filter(author__id=pk).select_related('order_related')
orders = offer.order_related

Or you could use a get, but i personally don’t do that since get statement breaks the code when data is not found but filter returns an empty array or query-set when data is not food and doesn’t break the code

offer = Offer.objects.get(author__id=pk).select_related('order_related')
orders = offer.order_related

CodePudding user response:

Thanks to Joshua Edward I have got this as a result:

views.py

class GetWorksByAuthor(ListModelMixin, GenericAPIView):

    serializer_class = OfferSerializer

    def get_queryset(self):
        author = self.kwargs['author']
        return Offer.objects.filter(author__id=author).select_related('order_related')

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

urls.py

urlpatterns = [
    path('works/author/<int:author>/',views.GetWorksByAuthor.as_view()),    
]
  • Related