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
The model serializer is just the same as the above serializer in the sense that it does the same job, only that it builds the serializer based on the model, making the creation of the serializer easier than building it normally. So in other words, explicitly defining CRUD methods (get, post,...) is not required.
The serializers in REST framework work very similarly to Django's Form and ModelForm classes. The two major serializers that are most popularly used are ModelSerializer and HyperLinkedModelSerialzer.
Django's serialization framework provides a mechanism for “translating” Django models into other formats. Usually these other formats will be text-based and used for sending Django data over a wire, but it's possible for a serializer to handle any format (text-based or not).
is_valid perform validation of input data and confirm that this data contain all required fields and all fields have correct types. If validation process succeded is_valid set validated_data dictionary which is used for creation or updating data in DB.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With