Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading