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
faker1
V2EX  ›  Python

Django ForeignKey 的问题求教

  •  
  •   faker1 · 2018-09-21 16:14:40 +08:00 · 1751 次点击
    这是一个创建于 2015 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如下 model

    class Region(models.Model):
        """ 区域 """
        name = models.CharField(max_length=30)
        created_at = models.DateTimeField(auto_now=True)
     
     class UserProfile(models.Model):
        """
        用户信息
        """
        user = models.OneToOneField(
       
        region = models.ForeignKey(Region, on_delete=models.CASCADE, null=True, blank=True)
        
    

    我想为 UserProfile 关联多个 region,这个怎么写啊,有点懵逼

    9 条回复    2018-09-23 16:57:47 +08:00
    hiths
        1
    hiths  
       2018-09-21 16:17:43 +08:00
    manytomany 应该可以的
    hiths
        2
    hiths  
       2018-09-21 16:18:28 +08:00
    @hiths 哦不对看错了。尴尬
    hiths
        3
    hiths  
       2018-09-21 16:22:31 +08:00
    @hiths 好像没错哈哈哈就用 manytomany...
    wuyifar
        4
    wuyifar  
       2018-09-21 16:28:05 +08:00
    为 UserProfile 关联多个 region 的意思是, 一条用户信息可以包含多个用户信息吗, 如果是的话,直接将外键设置在 Region 下 userprofile= models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, blank=True) 这样就是一个一对多的关系了。
    faker1
        5
    faker1  
    OP
       2018-09-21 16:54:28 +08:00
    @wuyifar , 但是暂时不能动结构,有办法可以实现我的目的吗?谢谢了
    welkinzh
        6
    welkinzh  
       2018-09-21 16:59:18 +08:00
    四楼的方法不能用吗。。。那你可以在 UserProfile 下添加 region1, region2, region3... 不
    uhayate
        7
    uhayate  
       2018-09-21 17:06:26 +08:00
    JSONField 了解一下,爱有几个 region 有几个。
    SmartKeyerror
        8
    SmartKeyerror  
       2018-09-22 00:19:26 +08:00 via Android
    一句话: 一对多的关联关系,关系保存在"多"的那张表中。ForeignKey 其实在数据库中为一个 id,如果是 user 有多个 region,那么 region 就是"多"关系。数据库的结构就是这样的:
    user:
    id username ...
    1 张三

    region:
    id name ... user_id
    1 中国 1
    2 广东 1
    这样一来张三就有多个区域了。
    wuyifar
        9
    wuyifar  
       2018-09-23 16:57:47 +08:00
    @faker1 不能改结构的话,可以加个表吗,可以的话就加个表,手动去关联
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3505 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 391ms · UTC 11:01 · PVG 19:01 · LAX 04:01 · JFK 07:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.