PUT/Update Foreign Key & Many To Many relationship with just pk, and NOT the whole object












0















I've got a User model that has a foreign key and many to many relationship with another model.



class User(AbstractUser):
'''
Custom User model. Countries is a list of countries associated with the
user. Home country is a single country object
'''
countries = models.ManyToManyField(
Country, blank=True, related_name='user_countries'
)
home = models.ForeignKey(
Country, on_delete=models.PROTECT, null=True,
related_name='home_country',
)


and



class Country(models.Model):
'''
Describes the countries, as well as territories of the world.
'''
name = models.CharField(max_length=255, null=True, blank=True)
top_level_domain = JSONField(null=True, blank=True)
alpha2code = models.CharField(max_length=255, null=True, blank=True)
alpha3code = models.CharField(max_length=255, null=True, blank=True)
calling_codes = JSONField(null=True, blank=True)
capital = models.CharField(max_length=255, null=True, blank=True)
alt_spellings = JSONField(null=True, blank=True)
region = models.CharField(max_length=255, null=True, blank=True)
subregion = models.CharField(max_length=255, null=True, blank=True)
population = models.IntegerField(null=True, blank=True)
latlng = JSONField(null=True, blank=True)
demonym = models.CharField(max_length=255, null=True, blank=True)
area = models.FloatField(null=True, blank=True)
gini = models.FloatField(null=True, blank=True)
timezones = JSONField(null=True, blank=True)
borders = JSONField(null=True, blank=True)
native_name = models.CharField(max_length=255, null=True, blank=True)
numeric_code= models.CharField(max_length=255, null=True, blank=True)
currencies = models.ManyToManyField(Currency)
languages = models.ManyToManyField(Language)
flag = models.CharField(max_length=255, null=True, blank=True)
regional_blocs = models.ManyToManyField(RegionalBloc, blank=True)
cioc = models.CharField(max_length=255, null=True, blank=True)

def __str__(self):
return self.name


The country model itself has a few many to many relationships, and so it is a nested object. When updating my user model with a PUT request, I can serialize my country object to just show the pk, and I can send the pk of the updated country/countries from my React axios request, but then when I axios GET my user object, it only displays country/countries.



On the otherhand, I can serialize my country objects as nested objects with all their fields and subfields, and then I get the data I want from an axios GET request, but then when I want to update my user object, I have to pass in a country object to my axios PUT instead of just a pk.



Is it possible serialize my country objects in their full nested beauty, BUT ALSO update/PUT my user model by just passing in the pk alone?



I'm updating my user object with select forms, and so it's easy to have an option with the value=pk, and then I can PUT request with just the value.



<option value="6">Andorra</option>


This is my custom User Detail serializer at the moment:



class UserDetailSerializer(UserDetailsSerializer):
'''
Custom serializer for the /rest-auth/user/ User Details Serializer.
'''
countries = CountrySerializer(many=True)
home = serializers.SlugRelatedField(slug_field='pk', queryset=Country.objects.all())

class Meta:
model = User
fields = ('pk', 'username', 'email', 'countries', 'home',)

'''
Updates the users object in the database. The username, email, countries(a
list of country objects) and home (country object), are set by a PUT
request from the frontend.
'''
def update(self, instance, validated_data):
country_names = [cdata['name'] for cdata in validated_data['countries']]
countries = Country.objects.filter(name__in=country_names)
instance.username = validated_data['username']
instance.email = validated_data['email']
instance.countries.set(countries)
instance.home = validated_data['home']
instance.save()
return instance


I'm serializing the home field by just the pk currently, which like I mentioned, makes it easy to PUT, but then in React the user object I GET has



home: 6


instead of



{
"id": 6,
"currencies": [
{
"code": "EUR",
"name": "European Euro",
"symbol": "€"
}
],
"languages": [
{
"iso639_1": "ca",
"name": "Catalan",
"native_name": "Català"
}
],
"regional_blocs": ,
"name": "Andorra",
"top_level_domain": [
".ad"
],
"alpha2code": "AD",
"alpha3code": "AND",
"calling_codes": [
"376"
],
"capital": "Andorra la Vella",
"alt_spellings": [
"AD",
"Principality of Andorra",
"Principat d'Andorra"
],
"region": "Europe",
"subregion": "Southern Europe",
"population": 78014,
"latlng": [
42.5,
1.5
],
"demonym": "Andorran",
"area": 468.0,
"gini": null,
"timezones": [
"UTC+01:00"
],
"borders": [
"FRA",
"ESP"
],
"native_name": "Andorra",
"numeric_code": "020",
"flag": "https://restcountries.eu/data/and.svg",
"cioc": "AND"
}









share|improve this question



























    0















    I've got a User model that has a foreign key and many to many relationship with another model.



    class User(AbstractUser):
    '''
    Custom User model. Countries is a list of countries associated with the
    user. Home country is a single country object
    '''
    countries = models.ManyToManyField(
    Country, blank=True, related_name='user_countries'
    )
    home = models.ForeignKey(
    Country, on_delete=models.PROTECT, null=True,
    related_name='home_country',
    )


    and



    class Country(models.Model):
    '''
    Describes the countries, as well as territories of the world.
    '''
    name = models.CharField(max_length=255, null=True, blank=True)
    top_level_domain = JSONField(null=True, blank=True)
    alpha2code = models.CharField(max_length=255, null=True, blank=True)
    alpha3code = models.CharField(max_length=255, null=True, blank=True)
    calling_codes = JSONField(null=True, blank=True)
    capital = models.CharField(max_length=255, null=True, blank=True)
    alt_spellings = JSONField(null=True, blank=True)
    region = models.CharField(max_length=255, null=True, blank=True)
    subregion = models.CharField(max_length=255, null=True, blank=True)
    population = models.IntegerField(null=True, blank=True)
    latlng = JSONField(null=True, blank=True)
    demonym = models.CharField(max_length=255, null=True, blank=True)
    area = models.FloatField(null=True, blank=True)
    gini = models.FloatField(null=True, blank=True)
    timezones = JSONField(null=True, blank=True)
    borders = JSONField(null=True, blank=True)
    native_name = models.CharField(max_length=255, null=True, blank=True)
    numeric_code= models.CharField(max_length=255, null=True, blank=True)
    currencies = models.ManyToManyField(Currency)
    languages = models.ManyToManyField(Language)
    flag = models.CharField(max_length=255, null=True, blank=True)
    regional_blocs = models.ManyToManyField(RegionalBloc, blank=True)
    cioc = models.CharField(max_length=255, null=True, blank=True)

    def __str__(self):
    return self.name


    The country model itself has a few many to many relationships, and so it is a nested object. When updating my user model with a PUT request, I can serialize my country object to just show the pk, and I can send the pk of the updated country/countries from my React axios request, but then when I axios GET my user object, it only displays country/countries.



    On the otherhand, I can serialize my country objects as nested objects with all their fields and subfields, and then I get the data I want from an axios GET request, but then when I want to update my user object, I have to pass in a country object to my axios PUT instead of just a pk.



    Is it possible serialize my country objects in their full nested beauty, BUT ALSO update/PUT my user model by just passing in the pk alone?



    I'm updating my user object with select forms, and so it's easy to have an option with the value=pk, and then I can PUT request with just the value.



    <option value="6">Andorra</option>


    This is my custom User Detail serializer at the moment:



    class UserDetailSerializer(UserDetailsSerializer):
    '''
    Custom serializer for the /rest-auth/user/ User Details Serializer.
    '''
    countries = CountrySerializer(many=True)
    home = serializers.SlugRelatedField(slug_field='pk', queryset=Country.objects.all())

    class Meta:
    model = User
    fields = ('pk', 'username', 'email', 'countries', 'home',)

    '''
    Updates the users object in the database. The username, email, countries(a
    list of country objects) and home (country object), are set by a PUT
    request from the frontend.
    '''
    def update(self, instance, validated_data):
    country_names = [cdata['name'] for cdata in validated_data['countries']]
    countries = Country.objects.filter(name__in=country_names)
    instance.username = validated_data['username']
    instance.email = validated_data['email']
    instance.countries.set(countries)
    instance.home = validated_data['home']
    instance.save()
    return instance


    I'm serializing the home field by just the pk currently, which like I mentioned, makes it easy to PUT, but then in React the user object I GET has



    home: 6


    instead of



    {
    "id": 6,
    "currencies": [
    {
    "code": "EUR",
    "name": "European Euro",
    "symbol": "€"
    }
    ],
    "languages": [
    {
    "iso639_1": "ca",
    "name": "Catalan",
    "native_name": "Català"
    }
    ],
    "regional_blocs": ,
    "name": "Andorra",
    "top_level_domain": [
    ".ad"
    ],
    "alpha2code": "AD",
    "alpha3code": "AND",
    "calling_codes": [
    "376"
    ],
    "capital": "Andorra la Vella",
    "alt_spellings": [
    "AD",
    "Principality of Andorra",
    "Principat d'Andorra"
    ],
    "region": "Europe",
    "subregion": "Southern Europe",
    "population": 78014,
    "latlng": [
    42.5,
    1.5
    ],
    "demonym": "Andorran",
    "area": 468.0,
    "gini": null,
    "timezones": [
    "UTC+01:00"
    ],
    "borders": [
    "FRA",
    "ESP"
    ],
    "native_name": "Andorra",
    "numeric_code": "020",
    "flag": "https://restcountries.eu/data/and.svg",
    "cioc": "AND"
    }









    share|improve this question

























      0












      0








      0








      I've got a User model that has a foreign key and many to many relationship with another model.



      class User(AbstractUser):
      '''
      Custom User model. Countries is a list of countries associated with the
      user. Home country is a single country object
      '''
      countries = models.ManyToManyField(
      Country, blank=True, related_name='user_countries'
      )
      home = models.ForeignKey(
      Country, on_delete=models.PROTECT, null=True,
      related_name='home_country',
      )


      and



      class Country(models.Model):
      '''
      Describes the countries, as well as territories of the world.
      '''
      name = models.CharField(max_length=255, null=True, blank=True)
      top_level_domain = JSONField(null=True, blank=True)
      alpha2code = models.CharField(max_length=255, null=True, blank=True)
      alpha3code = models.CharField(max_length=255, null=True, blank=True)
      calling_codes = JSONField(null=True, blank=True)
      capital = models.CharField(max_length=255, null=True, blank=True)
      alt_spellings = JSONField(null=True, blank=True)
      region = models.CharField(max_length=255, null=True, blank=True)
      subregion = models.CharField(max_length=255, null=True, blank=True)
      population = models.IntegerField(null=True, blank=True)
      latlng = JSONField(null=True, blank=True)
      demonym = models.CharField(max_length=255, null=True, blank=True)
      area = models.FloatField(null=True, blank=True)
      gini = models.FloatField(null=True, blank=True)
      timezones = JSONField(null=True, blank=True)
      borders = JSONField(null=True, blank=True)
      native_name = models.CharField(max_length=255, null=True, blank=True)
      numeric_code= models.CharField(max_length=255, null=True, blank=True)
      currencies = models.ManyToManyField(Currency)
      languages = models.ManyToManyField(Language)
      flag = models.CharField(max_length=255, null=True, blank=True)
      regional_blocs = models.ManyToManyField(RegionalBloc, blank=True)
      cioc = models.CharField(max_length=255, null=True, blank=True)

      def __str__(self):
      return self.name


      The country model itself has a few many to many relationships, and so it is a nested object. When updating my user model with a PUT request, I can serialize my country object to just show the pk, and I can send the pk of the updated country/countries from my React axios request, but then when I axios GET my user object, it only displays country/countries.



      On the otherhand, I can serialize my country objects as nested objects with all their fields and subfields, and then I get the data I want from an axios GET request, but then when I want to update my user object, I have to pass in a country object to my axios PUT instead of just a pk.



      Is it possible serialize my country objects in their full nested beauty, BUT ALSO update/PUT my user model by just passing in the pk alone?



      I'm updating my user object with select forms, and so it's easy to have an option with the value=pk, and then I can PUT request with just the value.



      <option value="6">Andorra</option>


      This is my custom User Detail serializer at the moment:



      class UserDetailSerializer(UserDetailsSerializer):
      '''
      Custom serializer for the /rest-auth/user/ User Details Serializer.
      '''
      countries = CountrySerializer(many=True)
      home = serializers.SlugRelatedField(slug_field='pk', queryset=Country.objects.all())

      class Meta:
      model = User
      fields = ('pk', 'username', 'email', 'countries', 'home',)

      '''
      Updates the users object in the database. The username, email, countries(a
      list of country objects) and home (country object), are set by a PUT
      request from the frontend.
      '''
      def update(self, instance, validated_data):
      country_names = [cdata['name'] for cdata in validated_data['countries']]
      countries = Country.objects.filter(name__in=country_names)
      instance.username = validated_data['username']
      instance.email = validated_data['email']
      instance.countries.set(countries)
      instance.home = validated_data['home']
      instance.save()
      return instance


      I'm serializing the home field by just the pk currently, which like I mentioned, makes it easy to PUT, but then in React the user object I GET has



      home: 6


      instead of



      {
      "id": 6,
      "currencies": [
      {
      "code": "EUR",
      "name": "European Euro",
      "symbol": "€"
      }
      ],
      "languages": [
      {
      "iso639_1": "ca",
      "name": "Catalan",
      "native_name": "Català"
      }
      ],
      "regional_blocs": ,
      "name": "Andorra",
      "top_level_domain": [
      ".ad"
      ],
      "alpha2code": "AD",
      "alpha3code": "AND",
      "calling_codes": [
      "376"
      ],
      "capital": "Andorra la Vella",
      "alt_spellings": [
      "AD",
      "Principality of Andorra",
      "Principat d'Andorra"
      ],
      "region": "Europe",
      "subregion": "Southern Europe",
      "population": 78014,
      "latlng": [
      42.5,
      1.5
      ],
      "demonym": "Andorran",
      "area": 468.0,
      "gini": null,
      "timezones": [
      "UTC+01:00"
      ],
      "borders": [
      "FRA",
      "ESP"
      ],
      "native_name": "Andorra",
      "numeric_code": "020",
      "flag": "https://restcountries.eu/data/and.svg",
      "cioc": "AND"
      }









      share|improve this question














      I've got a User model that has a foreign key and many to many relationship with another model.



      class User(AbstractUser):
      '''
      Custom User model. Countries is a list of countries associated with the
      user. Home country is a single country object
      '''
      countries = models.ManyToManyField(
      Country, blank=True, related_name='user_countries'
      )
      home = models.ForeignKey(
      Country, on_delete=models.PROTECT, null=True,
      related_name='home_country',
      )


      and



      class Country(models.Model):
      '''
      Describes the countries, as well as territories of the world.
      '''
      name = models.CharField(max_length=255, null=True, blank=True)
      top_level_domain = JSONField(null=True, blank=True)
      alpha2code = models.CharField(max_length=255, null=True, blank=True)
      alpha3code = models.CharField(max_length=255, null=True, blank=True)
      calling_codes = JSONField(null=True, blank=True)
      capital = models.CharField(max_length=255, null=True, blank=True)
      alt_spellings = JSONField(null=True, blank=True)
      region = models.CharField(max_length=255, null=True, blank=True)
      subregion = models.CharField(max_length=255, null=True, blank=True)
      population = models.IntegerField(null=True, blank=True)
      latlng = JSONField(null=True, blank=True)
      demonym = models.CharField(max_length=255, null=True, blank=True)
      area = models.FloatField(null=True, blank=True)
      gini = models.FloatField(null=True, blank=True)
      timezones = JSONField(null=True, blank=True)
      borders = JSONField(null=True, blank=True)
      native_name = models.CharField(max_length=255, null=True, blank=True)
      numeric_code= models.CharField(max_length=255, null=True, blank=True)
      currencies = models.ManyToManyField(Currency)
      languages = models.ManyToManyField(Language)
      flag = models.CharField(max_length=255, null=True, blank=True)
      regional_blocs = models.ManyToManyField(RegionalBloc, blank=True)
      cioc = models.CharField(max_length=255, null=True, blank=True)

      def __str__(self):
      return self.name


      The country model itself has a few many to many relationships, and so it is a nested object. When updating my user model with a PUT request, I can serialize my country object to just show the pk, and I can send the pk of the updated country/countries from my React axios request, but then when I axios GET my user object, it only displays country/countries.



      On the otherhand, I can serialize my country objects as nested objects with all their fields and subfields, and then I get the data I want from an axios GET request, but then when I want to update my user object, I have to pass in a country object to my axios PUT instead of just a pk.



      Is it possible serialize my country objects in their full nested beauty, BUT ALSO update/PUT my user model by just passing in the pk alone?



      I'm updating my user object with select forms, and so it's easy to have an option with the value=pk, and then I can PUT request with just the value.



      <option value="6">Andorra</option>


      This is my custom User Detail serializer at the moment:



      class UserDetailSerializer(UserDetailsSerializer):
      '''
      Custom serializer for the /rest-auth/user/ User Details Serializer.
      '''
      countries = CountrySerializer(many=True)
      home = serializers.SlugRelatedField(slug_field='pk', queryset=Country.objects.all())

      class Meta:
      model = User
      fields = ('pk', 'username', 'email', 'countries', 'home',)

      '''
      Updates the users object in the database. The username, email, countries(a
      list of country objects) and home (country object), are set by a PUT
      request from the frontend.
      '''
      def update(self, instance, validated_data):
      country_names = [cdata['name'] for cdata in validated_data['countries']]
      countries = Country.objects.filter(name__in=country_names)
      instance.username = validated_data['username']
      instance.email = validated_data['email']
      instance.countries.set(countries)
      instance.home = validated_data['home']
      instance.save()
      return instance


      I'm serializing the home field by just the pk currently, which like I mentioned, makes it easy to PUT, but then in React the user object I GET has



      home: 6


      instead of



      {
      "id": 6,
      "currencies": [
      {
      "code": "EUR",
      "name": "European Euro",
      "symbol": "€"
      }
      ],
      "languages": [
      {
      "iso639_1": "ca",
      "name": "Catalan",
      "native_name": "Català"
      }
      ],
      "regional_blocs": ,
      "name": "Andorra",
      "top_level_domain": [
      ".ad"
      ],
      "alpha2code": "AD",
      "alpha3code": "AND",
      "calling_codes": [
      "376"
      ],
      "capital": "Andorra la Vella",
      "alt_spellings": [
      "AD",
      "Principality of Andorra",
      "Principat d'Andorra"
      ],
      "region": "Europe",
      "subregion": "Southern Europe",
      "population": 78014,
      "latlng": [
      42.5,
      1.5
      ],
      "demonym": "Andorran",
      "area": 468.0,
      "gini": null,
      "timezones": [
      "UTC+01:00"
      ],
      "borders": [
      "FRA",
      "ESP"
      ],
      "native_name": "Andorra",
      "numeric_code": "020",
      "flag": "https://restcountries.eu/data/and.svg",
      "cioc": "AND"
      }






      django reactjs django-rest-framework axios






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 13 '18 at 17:58









      peter176peter176

      5110




      5110
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I was able to overwrite the to_representation function in my serializer similar to these instructions: Django Rest Framework receive primary key value in POST and return model object as nested serializer






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53286937%2fput-update-foreign-key-many-to-many-relationship-with-just-pk-and-not-the-who%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I was able to overwrite the to_representation function in my serializer similar to these instructions: Django Rest Framework receive primary key value in POST and return model object as nested serializer






            share|improve this answer




























              0














              I was able to overwrite the to_representation function in my serializer similar to these instructions: Django Rest Framework receive primary key value in POST and return model object as nested serializer






              share|improve this answer


























                0












                0








                0







                I was able to overwrite the to_representation function in my serializer similar to these instructions: Django Rest Framework receive primary key value in POST and return model object as nested serializer






                share|improve this answer













                I was able to overwrite the to_representation function in my serializer similar to these instructions: Django Rest Framework receive primary key value in POST and return model object as nested serializer







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 14 '18 at 11:51









                peter176peter176

                5110




                5110






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53286937%2fput-update-foreign-key-many-to-many-relationship-with-just-pk-and-not-the-who%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Full-time equivalent

                    Bicuculline

                    さくらももこ