coderholic / django-cities

Countries and cities of the world for Django projects
MIT License
921 stars 375 forks source link

Multiple objects returned while serializing using cities__name_std #126

Closed kishan3 closed 7 years ago

kishan3 commented 8 years ago

I have serializer like this: `class ExperienceSerializer(serializers.ModelSerializer):

    experience_type = ChoicesField(choices=Experience.EXPERIENCE_TYPE)
    location = serializers.SlugRelatedField(slug_field='name_std', queryset=City.objects.all())

`

Whenever I enter "Delhi" as location It fails with "get() returned more than one City -- it returned 2!" There are cities with same name so how to hanle this scenario?

blag commented 8 years ago

You will need to use the slug field for this - that's what it's there for after all!

    location = serializers.SlugRelatedField(slug_field='slug', queryset=City.objects.all())

Keep in mind that you will need to fill in that field yourself, but...

I've got some changes I need to push, and one of them is creating a unique constraint on the Place (abstract) model's slug field and giving each model a slugify() method. That should allow you to use the slug field to uniquely identify each city. I'll try to get that pushed either later today or Friday for you.

kishan3 commented 8 years ago

Hey @blag thanks for the information and help! Let me know if I can help you with anything.

blag commented 7 years ago

I'm currently working on #148 (adding slugs to all models), and that should get all fixed up and pushed Real Soon Now.

If you want to work on #125 (add fields for boundaries and import them), that would be very useful for a lot of people. Thanks!

blag commented 7 years ago

I just pushed version 0.5 to PyPI, so you should be able to upgrade using pip:

pip install --upgrade django-cities

That version adds slugs to models, and allows you to specify your own slugify() function for all django-cities objects if you don't want to use the default slugify function I wrote.

Since all of the building blocks are in place, and the default settings should handle this (or at least handle 90% of it), I'm closing this issue. Feel free to reopen it if you run into any issues. Cheers!

umair-tp commented 5 years ago

I am having a city field in User model which is actually a ForeignKey to City model. I am confused how to design serializer: I want the city to be writeable, which I can achieve by using SlugRelatedField but

  1. I want to return city name when get request is made, in SlugRelatedField slug_field is returned. source="city.name" is throwing error as it's detecting it as nested object
  2. I want to take city slug in patch request and update the city. There can be several city with same name, so slug_field="name" is returning multiple object and thus raising error.

Any suggestion ?