DRF序列化之ModelSerializer

前面我们通过DRF的APIView方法实现了序列化、前面我们提到了几个非常重要的概念,比如Serializer序列化和APIView。既然Django为我们提供了Form和ModelForm,那么在DRF里面有没有类似的方法呢?有的、下面我们再一起看看DRF提供的另外一个序列化方法:ModelSerializer。

# 官方示例
class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ['id', 'title', 'code', 'linenos', 'language', 'style']


# 实际代码
from rest_framework import serializers
from .models import Goods


class GoodsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Goods
        fields = ('name', 'goods_sn', 'click_num', 'sold_num', 'fav_num', 'goods_num')

ModelSerializer让我们省去了字段的添加、使代码更加精简;我们可以把需要实现序列化的字段添加到fields里面去。但是有没有一个办法可以把所有字段一次性都拿到呢?

from rest_framework import serializers
from .models import Goods


class GoodsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Goods
        # fields = ('name', 'goods_sn', 'click_num', 'sold_num', 'fav_num', 'goods_num')
        fields = "__all__"

注:我们可以通过上面的all参数一次性把所有字段都取出来;ModelSerializer还会自动把外键字段的ID显示出来。

img

既然ModelSerializer可以把外键的ID拿到、那如果我们想获取到外键的完整信息呢?怎么办?ModelSerializer可以帮我们自动实现呢?答案是可以的。我们可以通过Serializer的嵌套来实现:

from rest_framework import serializers
from .models import Goods, GoodsCategory


class GoodsCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        # fields = ('name', 'goods_sn', 'click_num', 'sold_num', 'fav_num', 'goods_num')
        fields = "__all__"


class GoodsSerializer(serializers.ModelSerializer):
    category = GoodsCategorySerializer()

    class Meta:
        model = Goods
        # fields = ('name', 'goods_sn', 'click_num', 'sold_num', 'fav_num', 'goods_num')
        fields = "__all__"

这里我们使用 category = GoodsCategorySerializer() 来覆盖默认的 category 外键字段。从下图我们可以看到、我们采用很简单的代码就实现了复杂的嵌套式序列化;这种能力是Django所不具备的。

img

推荐文章

52条评论

  1. I have read some excellent stuff here. Definitely worth bookmarking for revisiting. Roseann Claus Aeriela

  2. If you would like to get a great deal from this paragraph then you have to apply these methods to your won weblog. Marjie Elsworth Afton

  3. Fabulous, what a weblog it is! This website gives helpful information to us, keep it up. Hillary Derron Mungo

  4. You completed certain nice points there. I did a search on the matter and found mainly people will agree with your blog. Tressa Wait Zischke

  5. Pretty! This has been a really wonderful post. Many thanks for providing these details. Ashli Fairfax Klotz

  6. Awesome write-up. I am a regular visitor of your web site and appreciate you taking the time to maintain the nice site. I will be a regular visitor for a long time. Angeline Haydon Pettit

  7. Thanks for your pieces of advice. Will try to stick to them. Alina Basilius Lust

  8. Aplikasi yang bagus untuk membantu para usahawan dalam mengembangkan bisnisnya tanpa harus hire costumer service dan semakin cepat membalas chat pelanggan. Tedi Casey Procora

  9. Determining the best way to share your message means that you will have to make certain choices. Jacqui Farlee Rockel

  10. I have been exploring for a little bit for any high-quality articles or blog posts on this sort of house . Kay Shalom Balthazar

  11. I gotta bookmark this web site it seems very helpful very beneficial Clair Roi Lebna

  12. If you are going for best contents like I do, only go to see this web page all the time because it presents feature contents, thanks Kessia Ezekiel Grand

  13. one of our guests a short while ago encouraged the following website Miguela Enrique Bullen

  14. Of course, what a splendid blog and educative posts, I will bookmark your site. Best Regards! Ardra Ozzy Sewole

  15. You made some respectable factors there. I viewed on the web for the problem and discovered most individuals will accompany with your web site. Rosemonde Cesare Merissa

  16. quick heads up. The words in your content seem to be running off the Cathryn Sig Ballman

  17. I really like your writing style, great information, thanks for posting : D. Hermina Sergent Tersina Kippy Fran Marella

  18. I was excited to find this page. I need to to thank you for ones time just for this fantastic read!! I definitely appreciated every part of it and i also have you saved to fav to see new information in your website. Janeczka Benn Ferren

  19. What a lovely piece! I felt truly happy for you the whole time I was reading. Well done Olympe Rockwell Barrett

  20. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You definitely know what youre talking about, why throw away your intelligence on just posting videos to your weblog when you could be giving us something informative to read? Doe Kingston Clyte

  21. Training alone will help you concentrate on the skills where you need the most practice. Zara Teddie Peder

  22. We are a group of volunteers and starting a new scheme in our community. Your website provided us with valuable information to work on. You have done an impressive job and our entire community will be thankful to you. Emmaline Giacopo Xenophon

  23. ilmaiset videot, ilmaiset pornovideot, ilmaiset porno videot, porno video, porno videot Michaella Silvester Nicoline

  24. Impressive! I am amazed at how well you use words to get your point across. I would be interested in reading more of your work. Annissa Keenan Koffler Lu Ozzie Walther

  25. Once a ref whistles that the ball is dead, you have 40 seconds before you have to start a play. Jannel Dan Kingdon

  26. This text is invaluable. Where can I find out more? Gerladina Clarance Burris

  27. hi!,I love your writing very so much! percentage we communicate extra approximately your article on AOL? I need an expert in this house to solve my problem. Maybe that is you! Looking forward to look you. Elfrieda Garrick Marjorie

  28. Nice blog here! Additionally your web site quite a bit up fast! What host are you the usage of? Can I am getting your associate hyperlink in your host? I wish my website loaded up as quickly as yours lol Lilas Travis Rozelle

  29. Magnificent beat ! I would like to apprentice while you amend your web site, how could i subscribe for a blog website? The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear idea Zonnya Saxe Erfert

  30. Incredible points. Solid arguments. Keep up the good work.| Michaelina Granville Sanborn

  31. Some really choice posts on this internet site , saved to my bookmarks . Margit Ellerey Ern

  32. Hey! This is my 1st comment here so I just wanted to give a quick shout out and say I really enjoy reading your blog posts. Can you suggest any other blogs/websites/forums that go over the same topics? Thank you so much!| Pavia Windham Silvestro

  33. Having read this I believed it was very informative. I appreciate you taking the time and energy to put this content together. I once again find myself spending a lot of time both reading and leaving comments. But so what, it was still worth it! Merrily Bordy Lynn

  34. I just could not go away your website before suggesting that I extremely loved the standard information an individual supply on your visitors? Is gonna be back steadily in order to investigate cross-check new posts. Deerdre Pasquale Scoter

  35. Awesome post. I am a normal visitor of your site and appreciate you taking the time to maintain the excellent site. I will be a regular visitor for a long time. Hazel Elsworth Monafo

  36. I will install a privacy tint and would only use it from home to the range. I agree with the under seat or the tool box gun rack in trucks because the firearm is concealed. Cecily Lyman Souza

  37. thanks for the tutorial. It worked once I got out of my own way. Thanks. Florie Owen Moriarty

  38. Hey, I think your website might be having browser compatibility issues. When I look at your blog in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, great blog! Edwina Kristoffer Colwin

  39. Great article. I am experiencing many of these issues as well.. Stephine Phil Mandych

  40. Curabitur urna tortor, dapibus eu nisi eu, pretium interdum diam. Nunc in interdum tellus. Tabbitha Burton Galvan

  41. I used to be able to find good information from your content. Ericha Booth Dahle

  42. Merely wanna remark that you have a very decent site, I like the layout it actually stands out. Dyanna Filberte Gabriel

  43. Attractive portion of content. I simply stumbled upon your site and in accession capital to claim that I acquire actually enjoyed account your blog posts. Any way I will be subscribing in your augment and even I fulfillment you get admission to consistently rapidly. Claude Odey Kwabena

  44. Hello there. I found your website by the use of Google while looking for a similar topic, your website came up. It appears to be great. I have bookmarked it in my google bookmarks to come back then. Cassi Nate Stultz

  45. This excellent website really has all of the information I needed about this subject and didn?t know who to ask. Haleigh Bard Morgenthaler

  46. Wow, incredible blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your web site is fantastic, as well as the content! Mariejeanne Payton Read

  47. Hi there. I found your website by way of Google while searching for a similar topic, your site came up. It seems to be good. I have bookmarked it in my google bookmarks to come back then. Leena Hilarius Whatley

  48. I do not even know how I ended up here, but I thought this post was great. Katee Berty Antebi

  49. Excellent post however , I was wanting to know if you
    could write a litte more on this subject? I’d be very thankful if you could elaborate a little bit
    further. Many thanks!

  50. Hello There. I found your weblog the use of
    msn. This is a very neatly written article. I will make sure to bookmark it
    and return to learn more of your useful info. Thanks for the post.
    I’ll certainly return.

发表评论

邮箱地址不会被公开。 必填项已用*标注