V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Aug 16, 2018 · 2682 views
    This topic created in 2816 days ago, the information mentioned may be changed or developed.
    我在使用 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 replies    2018-08-17 09:24:40 +08:00
    junezk
        2
    junezk  
    OP
       Aug 17, 2018
    @dalang 谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2364 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 10:33 · PVG 18:33 · LAX 03:33 · JFK 06:33
    ♥ Do have faith in what you're doing.