nithin singh Gm
nithin singh Gm

Reputation: 129

How can i have two models in one serializer in django

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

Upvotes: 8

Views: 9199

Answers (1)

Enthusiast Martin
Enthusiast Martin

Reputation: 3091

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)

Upvotes: 11

Related Questions