zoukankan      html  css  js  c++  java
  • Django配合MySQL学习Django模型外键的建立和使用

    Django 模型建立外键


    在模型中建立外键是很简单的,基本操作如下

    class Table(models.Model)
        column_name = models.ForeignKey(other-TableClassName)
    

    来看看这个模型(models.py)是啥:

    from django.db import models
    
    # Create your models here.
    class Score(models.Model):
        sid =   models.CharField(max_length=20,primary_key=True)
        value = models.IntegerField()
        class meta:
            db_table = "siteScore"
        def __unicode__(self):
            return self.name
    
    class Student(models.Model):
        id = models.IntegerField(primary_key=True)
        score = models.ForeignKey(Score)
        name = models.CharField(max_length=10)
    

    Django 外键的使用,插入和查询


    这个就不多说了,直接上代码:

    from django.shortcuts import render
    from django.http import HttpResponse
    from models import Score,Student
    # Create your views here.
    
    def insertScore(request):
        sid = request.GET['sid']
        value = request.GET["value"]
        Score.objects.create(sid=sid, value=value)
        return HttpResponse("ok")
    def insertStudent(request):
        pid = request.GET['pid']
        sid = request.GET['sid']
        name = request.GET["name"]
        psid = Score.objects.get(sid=sid)
        Student.objects.create(id=int(pid),score=psid, name=name)
        return HttpResponse("ok")
    def search(request):
        name = request.GET["name"]
        student = Student.objects.get(name=name)
        score = student.score.value
        string = "%s %s"%(name, score)
        return HttpResponse(string)
    


  • 相关阅读:
    bzoj1663: [Usaco2006 Open]赶集
    bzoj1662: [Usaco2006 Nov]Round Numbers 圆环数
    [bzoj3771]Triple
    [bzoj1477]青蛙的约会
    [bzoj2299][HAOI2011]向量
    [2017.4.7校内训练赛by hzwer]
    [bzoj2456]mode
    [bzoj2120]数颜色
    [bzoj3668][Noi2014]起床困难综合症/[洛谷3613]睡觉困难综合症
    [4.6校内训练赛]
  • 原文地址:https://www.cnblogs.com/KevinGeorge/p/9152293.html
Copyright © 2011-2022 走看看