Search code examples
pythondjangodjango-rest-frameworkdjango-serializer

Django Rest API: Serializer won't show Foreign Key Field values


I'm trying to list the values of FacilityAddressSerializer within the FacilitySearchSerializer. This is what i tried. I get all the values of the FacilitySearchSerializer but the values of the FacilityAddressSerializer are showing as Null:

serializers.py

class FacilityAddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = FacilityAddress
        fields = (
            "id",
            "PrimaryAddress",
            "SecondaryAddress",
            "City",
            "RegionOrState",
            "PostalCode",
            "Geolocation",
            "AddressInfo"
        )

class FacilitySearchSerializer(serializers.ModelSerializer):
    AddressInfo = FacilityAddressSerializer(source="fa")
    class Meta:
        model = Facility
        fields = (
            "id",
            "Name",
            "AddressInfo",
            "ListingVerified",
            "mainimage",
            "AdministratorCell",
            "Capacity",
            "PriceRangeMin",
            "PriceRangeMax",
        )
        read_only_fields = ("id", "Name", "ListingVerified", "mainimage", "AdministratorCell", "Capacity", "FeaturedVideo", "PriceRangeMin", "PriceRangeMax")

models.py

class Facility(models.Model):
    Name = models.CharField(max_length=150, null=True, blank=False)
    mainimage = models.ImageField(null=True, blank=True)
    Capacity = models.IntegerField(null=True, blank=True)
    TelephoneNumber = models.CharField(max_length=30, null=True, blank=True)
    AdministratorCell = PhoneNumberField(null=True, blank=True)
    PriceRangeMin = models.IntegerField(null=True, blank=True)
    PriceRangeMax = models.IntegerField(null=True, blank=True)

class FacilityAddress(models.Model):
    PrimaryAddress = models.CharField(max_length=150, null=True, blank=True)
    SecondaryAddress = models.CharField(max_length=150, null=True, blank=True)
    City = models.CharField(max_length=150, null=True, blank=True)
    RegionOrState = models.CharField(max_length=50, null=True, blank=True)
    PostalCode = models.CharField(max_length=30, null=True, blank=True)
    Geolocation = models.CharField(max_length=30, null=True, blank=True)
    AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE, related_name='fa')

Solution

  • It works after i added (many=True) next to the source=fa. I thought i didn't need that since i'm using foreign key fields and not manytomany fields but i guess i was wrong.