Django配合MySQL学习Django模型外键的建立和使用

时间:2023-03-09 15:34:23
Django配合MySQL学习Django模型外键的建立和使用

Django 模型建立外键


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

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

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

Django配合MySQL学习Django模型外键的建立和使用

Django配合MySQL学习Django模型外键的建立和使用

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)

Django配合MySQL学习Django模型外键的建立和使用

Django配合MySQL学习Django模型外键的建立和使用