[Fixed]-Display foreign key in parent class

1👍

When you specify the foreign key relationship for Rental in your Gallery model the related_name you specify automatically defines a field on the Rental object. The name of that field is whatever you set related_name to, in this case rent.

The important thing to understand here is that the related_name will be attached to the opposite side of the relationship from where the key is declared in your models. Because the related name is going to be a property of a Rental object, a better name for it might be galleries in your example.

Assuming you change the related_name in your models from rental to galleries, you can define your Rental serializer to output a list of associated galleries:

class RentalSerializer(serializers.ModelSerializer):
    user = serializers.ReadOnlyField(source='user.username')
    galleries = GallerySerializer(many=True, read_only=True)
    class Meta:
        model = Rental
        fields = ('user', 'name', 'phone_number','galleries')    

By declaring a GallerySerializer with the same name as the related_name defined in your foreign key relationship, it will automatically find only galleries which are associated with the Rental being serialized.

In another example:

Let’s say you have several Eggs in a Basket. We would want to create a many-to-one relationship between Eggs and a Basket and would accomplish this by creating a foreign-key relationship between the two. That would be in the form of storing the ID of the associated Basket for each Egg.

In Django, we would declare that foreign key on the Egg model. This allows us to access the basket that an egg is in via egg.basket. We also want to determine what eggs are in a particular basket. We do that by defining a related_name on the foreign-key field. This tells Django what the field linking the basket to all its contained eggs should be called. Since this field refers to all eggs in a basket, we would call it eggs.

In code:

class Basket(models.Model):
    color = models.CharField()

class Egg(models.Model):
    color = models.CharField()
    basket = models.ForeignKey(Basket, related_name="eggs")

Leave a comment