Search code examples
djangoinner-join

How to inner join two models in django?


class AvailableOptions(models.Model):
    name = models.CharField(max_length=20, default="")
    image = models.ImageField(upload_to=upload_to, blank=True, null=True)

class Stock(models.Model):
     name = models.ForeignKey(
        AvailableOptions, on_delete=models.CASCADE, related_name="Stock")
        quantity = models.IntegerField(null=False, default="")
        created_at = models.DateTimeField(auto_now_add=True)

How do I query to inner join the two models for name and quantity from the second model and image from the first model?

I tried this in my view but it only returned the second model's fields.

@api_view(['GET'])
def testview(request):
    query = Stock.objects.select_related('name')
    data = serializers.serialize('json', query )
    return Response(data)

Solution

  • There are many ways for visualizing the ForeignKey data. One of the way is that, you can define a serializer with depth meta attribute. Like this:

    class StockSerializer(serializers.ModelSerializer):
        class Meta:
            model = Stock
            fields = ['name', 'quantity ', 'created_at']
            depth = 1
    

    Then use it in the view:

    @api_view(['GET'])
    def testview(request):
        query = Stock.objects.select_related('name')
        data = StockSerializer(query, many=True)
        return Response(data)
    

    If you want to get the name and image information from AvailableOptions (like a flat represenation), you can use source for that:

    class StockSerializer(serializers.ModelSerializer):
        name = serializers.CharField(source='name.name', read_only=True)  # will only return the name
        image = serializers.ImageField(source='name.image', read_only=True)
        class Meta:
            model = Stock
            fields = ['name', 'quantity ', 'image']
        
    

    And use the serializer in the view as shared in previous section of the answer.