How can i have two models in one serializer in django
Asked Answered
Y

1

8

I created API Views using django rest framework, I have a model which icsconsist of list of states in it and it associates with another model called country by the help of country(which consist of list countries) foreignkey I am trying to insert new state (for example: Cherries under category of sweets, Burger under category of Junkfood, exactly as "State under category of countries") but i am getting only state input form and not getting countries to select and associate,

## Heading ##
#model code---
class states(models.Model):
    state = models.CharField(max_length=15)
    country = models.ForeignKey(countries, on_delete=models.PROTECT)

#serializers code---
class StatesDetailSerializer(ModelSerializer):
    class Meta:
        model = states
        fields= '__all__'
        depth = 1

#viewsets code ------
class StateCreateAPIView(CreateAPIView):
    queryset = states.objects.all()
    serializer_class = StatesDetailSerializer

I had attached a image, teach me how can i get countries data and to associate with states.how can i get list of countries to select and tag to states image here

Yongyoni answered 13/7, 2018 at 11:18 Comment(0)
R
11

Extend your serializer to include country field like this

class StatesDetailSerializer(ModelSerializer):

    country = serializers.PrimaryKeyRelatedField(queryset=countries.objects.all()) 

    class Meta:
        model = states
        fields= ( 'country', ** plus all the fields you want **)
        depth = 1

note: don't use __all__ for the fields. It is always better to explicitly state which fields you want to serialize ( to avoid potential vulnerabilities in your application)

Rashad answered 13/7, 2018 at 11:27 Comment(1)
Dear Enthusiast martin thank you very much, it workedYongyoni

© 2022 - 2024 — McMap. All rights reserved.