V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
junezk
V2EX  ›  Python

django RESTframework 做序列化,定义序列化类时怎么自己指向自己。

  •  
  •   junezk · 2018-08-16 21:46:42 +08:00 · 1902 次点击
    这是一个创建于 2073 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我在使用 django RESTframework 做序列化时遇到定义类时需要自己指向自己的情况。

    我在 django 中定义了一个类型的 model:

    class Channel(models.Model):
      """
      分类
      """
       name = models.CharField(verbose_name="分类名称", max_length=40)
       display_name = models.CharField(verbose_name="显示名称", max_length=40)
       parent = models.ForeignKey("Channel", null=True, blank=True, related_name="sub_channels", on_delete=models.SET_NULL)


    Channel 对象的 parent 属性可以指向自己类型的对象。

    做序列化时,就要定义
    class ChannelSerializer(serializers.ModelSerializer):
       parent = ChannelSerializer(read_only=True)

       class Meta:
         model = Channel
         fields = '__all__'
    这样的代码,这就不符合 Python 的语法了。
    请问如何定义这种自己指向自己的类的定义。
    2 条回复    2018-08-17 09:24:40 +08:00
    junezk
        2
    junezk  
    OP
       2018-08-17 09:24:40 +08:00
    @dalang 谢谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1221 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 18:07 · PVG 02:07 · LAX 11:07 · JFK 14:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.