Devinwon / article

0 stars 0 forks source link

关联查询 #20

Open Devinwon opened 6 years ago

Devinwon commented 6 years ago

models.py OnetoOne

from django.db import models from django.contrib.auth.models import User

class Uprofile(models.Model):
    belong=models.OneToOneField(User,related_name='profile',on_delete=models.CASCADE)
    weixin=models.CharField(max_length=100)
    qq=models.CharField(max_length=20)
    phone=models.CharField(max_length=11)
python manage.py shell
>>>from django.contrib.auth.models import User
>>>from login.models import *
>>>user=User.objects.get(username='admin')
>>>ufile=Uprofile.objects.get(belong=user)
>>>ufile.qq
'110'
>>>ufile.qq='11111'
>>>ufile.save()
>>>ufile.qq
11111

Foreign

class Host(models.Model):
    name=models.CharField(max_length=100)

    class Meta:
        verbose_name='Host'
        verbose_name_plural=verbose_name

    def __str__(self):
        return self.name

# 功能
class Fun(models.Model):
    groupType={
    ('1',"超级计算"),
    ('2',"普通计算"),
    ('3',"用户娱乐"),
    }
    groupName=models.CharField(choices=groupType,max_length=100)
    host=models.ForeignKey(Host,related_name='host',on_delete=models.CASCADE)

18 04 16 2210_1

>>> from login.models import Host
>>> hst=Host.objects.get(name='PC001')
>>> hst
<Host: PC001>
>>> hst.host.all()
<QuerySet [<Fun: Fun object (1)>, <Fun: Fun object (2)>]>
>>> hst.host.all()[0]
<Fun: Fun object (1)>
>>> hst.host.all()[0].groupType
{('2', '普通计算'), ('1', '超级计算'), ('3', '用户娱乐')}
>>> hst.host.all()[0].groupName
'1'
>>> hst.host.all()[1].groupName
'2'

Notice:

hst.host.all()