Overriding PrimaryKeyRelatedField to serialize a null RelatedField object based on requestHow to sort a list of objects based on an attribute of the objects?null object in Python?Django REST framework: non-model serializerSerializer as Field is not visible in jsonDjango DRF serializer on PrimaryKeyRelatedFieldDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerEmpty response when returning a user's unread FriendshipRequest DRFHow to expose some specific fields of model_b based on a field of model_a?Django rest serializer not serializing related fieldsHow to remove Django redundant inner join

Relation between Frobenius, spectral norm and sum of maxima

Why are electrically insulating heatsinks so rare? Is it just cost?

Modeling an IPv4 Address

How to say job offer in Mandarin/Cantonese?

How do you know if an analog film camera is still working?

Which models of the Boeing 737 are still in production?

What's the output of a record cartridge playing an out-of-speed record

Is the month field really deprecated?

Animated Series: Alien black spider robot crashes on Earth

Show that if two triangles built on parallel lines, with equal bases have the same perimeter only if they are congruent.

How does one intimidate enemies without having the capacity for violence?

Dragon forelimb placement

How can I make my BBEG immortal short of making them a Lich or Vampire?

What is the offset in a seaplane's hull?

same font throughout bibliography

How to test if a transaction is standard without spending real money?

In Japanese, what’s the difference between “Tonari ni” (となりに) and “Tsugi” (つぎ)? When would you use one over the other?

Is it possible to do 50 km distance without any previous training?

Explain the parameters before and after @ in the treminal

What are the differences between the usage of 'it' and 'they'?

Is it legal for company to use my work email to pretend I still work there?

Shell script not opening as desktop application

Email Account under attack (really) - anything I can do?

How do we improve the relationship with a client software team that performs poorly and is becoming less collaborative?



Overriding PrimaryKeyRelatedField to serialize a null RelatedField object based on request


How to sort a list of objects based on an attribute of the objects?null object in Python?Django REST framework: non-model serializerSerializer as Field is not visible in jsonDjango DRF serializer on PrimaryKeyRelatedFieldDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerEmpty response when returning a user's unread FriendshipRequest DRFHow to expose some specific fields of model_b based on a field of model_a?Django rest serializer not serializing related fieldsHow to remove Django redundant inner join






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















Can anyone suggest how I can serialize the following type of null related field to give a serialized JSON object list which isn't null on get request



class SomeModel(models.Model):
a_fk = models.ForeignKey(ForeignObj1, null=True, on_delete=models.CASCADE)
b_fk = models.ForeignKey(ForeignObj2, null=True, on_delete=models.CASCADE)


class SomeSerializer(serializers.ModelSerializer):
class Meta:
model = SomeModel
fields = ['a_fk', 'b_fk']


What I get/see in browsable API JSON is




"a_fk": null,
"b_fk": null



but the fields queryset are fetched on the browsable API form for POST request just like normal django forms



What I will like to see is the actual list of available queryset objects on those fields returned on get request, even though it's null, if I override the PrimaryKeyRelatedField init(), which I did, printing the fields still returned empty queryset, which means it's still treating the field as null.



I have gone through the source codes and still can't figure out how to make this happen dynamically on get request



P.S The fields have to remain null due to some business use case. Any nudge in the right direction will be greatly appreciated



my view for now looks like this



class SomeViewSet(viewsets.ModelViewSet):
queryset = Some.objects.all()
serializer_class = SomeSerializer


I also have another @action getter view embedded within a separate ModelViewSet, trying to get with request as well, still returning the same null objects.



After searching for hours, I think, the appropriate question should have been, how do I create a choice iterable list from a null PrimaryKeyRelatedField, again a nudge in the right direction will be super appreciated...










share|improve this question
























  • What does your views.py look like?

    – Waket Zheng
    Mar 9 at 3:57











  • @Wakek Zheng, I just updated my post with the view

    – Ibraheem Kolawole
    Mar 9 at 5:27











  • See django-rest-framework.org/api-guide/relations -- define a Serializer subclass for each object type and in SomeSerializer specify a = Obj1Serializer(many=True)

    – Mark R.
    Mar 9 at 8:43











  • @Mark R, what you suggested will work for a reverse relation, I am not dealing with a reverse relation case. I am dealing with a case where the fk's need to be selected in options on a form, like it can be selected on Browsable API form. So the f'k's pretty much have to be there.

    – Ibraheem Kolawole
    Mar 9 at 9:00

















0















Can anyone suggest how I can serialize the following type of null related field to give a serialized JSON object list which isn't null on get request



class SomeModel(models.Model):
a_fk = models.ForeignKey(ForeignObj1, null=True, on_delete=models.CASCADE)
b_fk = models.ForeignKey(ForeignObj2, null=True, on_delete=models.CASCADE)


class SomeSerializer(serializers.ModelSerializer):
class Meta:
model = SomeModel
fields = ['a_fk', 'b_fk']


What I get/see in browsable API JSON is




"a_fk": null,
"b_fk": null



but the fields queryset are fetched on the browsable API form for POST request just like normal django forms



What I will like to see is the actual list of available queryset objects on those fields returned on get request, even though it's null, if I override the PrimaryKeyRelatedField init(), which I did, printing the fields still returned empty queryset, which means it's still treating the field as null.



I have gone through the source codes and still can't figure out how to make this happen dynamically on get request



P.S The fields have to remain null due to some business use case. Any nudge in the right direction will be greatly appreciated



my view for now looks like this



class SomeViewSet(viewsets.ModelViewSet):
queryset = Some.objects.all()
serializer_class = SomeSerializer


I also have another @action getter view embedded within a separate ModelViewSet, trying to get with request as well, still returning the same null objects.



After searching for hours, I think, the appropriate question should have been, how do I create a choice iterable list from a null PrimaryKeyRelatedField, again a nudge in the right direction will be super appreciated...










share|improve this question
























  • What does your views.py look like?

    – Waket Zheng
    Mar 9 at 3:57











  • @Wakek Zheng, I just updated my post with the view

    – Ibraheem Kolawole
    Mar 9 at 5:27











  • See django-rest-framework.org/api-guide/relations -- define a Serializer subclass for each object type and in SomeSerializer specify a = Obj1Serializer(many=True)

    – Mark R.
    Mar 9 at 8:43











  • @Mark R, what you suggested will work for a reverse relation, I am not dealing with a reverse relation case. I am dealing with a case where the fk's need to be selected in options on a form, like it can be selected on Browsable API form. So the f'k's pretty much have to be there.

    – Ibraheem Kolawole
    Mar 9 at 9:00













0












0








0








Can anyone suggest how I can serialize the following type of null related field to give a serialized JSON object list which isn't null on get request



class SomeModel(models.Model):
a_fk = models.ForeignKey(ForeignObj1, null=True, on_delete=models.CASCADE)
b_fk = models.ForeignKey(ForeignObj2, null=True, on_delete=models.CASCADE)


class SomeSerializer(serializers.ModelSerializer):
class Meta:
model = SomeModel
fields = ['a_fk', 'b_fk']


What I get/see in browsable API JSON is




"a_fk": null,
"b_fk": null



but the fields queryset are fetched on the browsable API form for POST request just like normal django forms



What I will like to see is the actual list of available queryset objects on those fields returned on get request, even though it's null, if I override the PrimaryKeyRelatedField init(), which I did, printing the fields still returned empty queryset, which means it's still treating the field as null.



I have gone through the source codes and still can't figure out how to make this happen dynamically on get request



P.S The fields have to remain null due to some business use case. Any nudge in the right direction will be greatly appreciated



my view for now looks like this



class SomeViewSet(viewsets.ModelViewSet):
queryset = Some.objects.all()
serializer_class = SomeSerializer


I also have another @action getter view embedded within a separate ModelViewSet, trying to get with request as well, still returning the same null objects.



After searching for hours, I think, the appropriate question should have been, how do I create a choice iterable list from a null PrimaryKeyRelatedField, again a nudge in the right direction will be super appreciated...










share|improve this question
















Can anyone suggest how I can serialize the following type of null related field to give a serialized JSON object list which isn't null on get request



class SomeModel(models.Model):
a_fk = models.ForeignKey(ForeignObj1, null=True, on_delete=models.CASCADE)
b_fk = models.ForeignKey(ForeignObj2, null=True, on_delete=models.CASCADE)


class SomeSerializer(serializers.ModelSerializer):
class Meta:
model = SomeModel
fields = ['a_fk', 'b_fk']


What I get/see in browsable API JSON is




"a_fk": null,
"b_fk": null



but the fields queryset are fetched on the browsable API form for POST request just like normal django forms



What I will like to see is the actual list of available queryset objects on those fields returned on get request, even though it's null, if I override the PrimaryKeyRelatedField init(), which I did, printing the fields still returned empty queryset, which means it's still treating the field as null.



I have gone through the source codes and still can't figure out how to make this happen dynamically on get request



P.S The fields have to remain null due to some business use case. Any nudge in the right direction will be greatly appreciated



my view for now looks like this



class SomeViewSet(viewsets.ModelViewSet):
queryset = Some.objects.all()
serializer_class = SomeSerializer


I also have another @action getter view embedded within a separate ModelViewSet, trying to get with request as well, still returning the same null objects.



After searching for hours, I think, the appropriate question should have been, how do I create a choice iterable list from a null PrimaryKeyRelatedField, again a nudge in the right direction will be super appreciated...







python django django-rest-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 9 at 8:36







Ibraheem Kolawole

















asked Mar 9 at 3:18









Ibraheem KolawoleIbraheem Kolawole

1115




1115












  • What does your views.py look like?

    – Waket Zheng
    Mar 9 at 3:57











  • @Wakek Zheng, I just updated my post with the view

    – Ibraheem Kolawole
    Mar 9 at 5:27











  • See django-rest-framework.org/api-guide/relations -- define a Serializer subclass for each object type and in SomeSerializer specify a = Obj1Serializer(many=True)

    – Mark R.
    Mar 9 at 8:43











  • @Mark R, what you suggested will work for a reverse relation, I am not dealing with a reverse relation case. I am dealing with a case where the fk's need to be selected in options on a form, like it can be selected on Browsable API form. So the f'k's pretty much have to be there.

    – Ibraheem Kolawole
    Mar 9 at 9:00

















  • What does your views.py look like?

    – Waket Zheng
    Mar 9 at 3:57











  • @Wakek Zheng, I just updated my post with the view

    – Ibraheem Kolawole
    Mar 9 at 5:27











  • See django-rest-framework.org/api-guide/relations -- define a Serializer subclass for each object type and in SomeSerializer specify a = Obj1Serializer(many=True)

    – Mark R.
    Mar 9 at 8:43











  • @Mark R, what you suggested will work for a reverse relation, I am not dealing with a reverse relation case. I am dealing with a case where the fk's need to be selected in options on a form, like it can be selected on Browsable API form. So the f'k's pretty much have to be there.

    – Ibraheem Kolawole
    Mar 9 at 9:00
















What does your views.py look like?

– Waket Zheng
Mar 9 at 3:57





What does your views.py look like?

– Waket Zheng
Mar 9 at 3:57













@Wakek Zheng, I just updated my post with the view

– Ibraheem Kolawole
Mar 9 at 5:27





@Wakek Zheng, I just updated my post with the view

– Ibraheem Kolawole
Mar 9 at 5:27













See django-rest-framework.org/api-guide/relations -- define a Serializer subclass for each object type and in SomeSerializer specify a = Obj1Serializer(many=True)

– Mark R.
Mar 9 at 8:43





See django-rest-framework.org/api-guide/relations -- define a Serializer subclass for each object type and in SomeSerializer specify a = Obj1Serializer(many=True)

– Mark R.
Mar 9 at 8:43













@Mark R, what you suggested will work for a reverse relation, I am not dealing with a reverse relation case. I am dealing with a case where the fk's need to be selected in options on a form, like it can be selected on Browsable API form. So the f'k's pretty much have to be there.

– Ibraheem Kolawole
Mar 9 at 9:00





@Mark R, what you suggested will work for a reverse relation, I am not dealing with a reverse relation case. I am dealing with a case where the fk's need to be selected in options on a form, like it can be selected on Browsable API form. So the f'k's pretty much have to be there.

– Ibraheem Kolawole
Mar 9 at 9:00












0






active

oldest

votes












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%2f55073661%2foverriding-primarykeyrelatedfield-to-serialize-a-null-relatedfield-object-based%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















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%2f55073661%2foverriding-primarykeyrelatedfield-to-serialize-a-null-relatedfield-object-based%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

Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

Posting a File and Associated Data to a RESTful WebService preferably as JSON2019 Community Moderator ElectionREST URI convention - Singular or plural name of resource while creating itUploading both data and files in one form using Ajax?How do I upload a file with metadata using a REST web service?REST API - file (ie images) processing - best practicesSpring: JSON data and file in the same requestREST API Put large dataPosting a file and JSON data to Spring rest serviceRESTful Web Service Upload/Download Large Data With JSONREST API Design sending JSON data and a file to the api in same requestPost JSONArray to REST servicePUT vs. POST in RESTParsing values from a JSON file?JavaScript/jQuery to download file via POST with JSON dataHow do I upload a file with metadata using a REST web service?How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?Separate REST JSON API server and client?what's the correct way to send a file from REST web service to client?How do I write JSON data to a file?What is “406-Not Acceptable Response” in HTTP?REST API - file (ie images) processing - best practices

How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page