如何在django中编写连接查询?

时间:2017-10-01 17:54:04

标签: django django-models

我已经搜索了几个小时,但无法理解如何编写sql join(raw或ORM)相关查询。

下面是我的模型,其中有两个表sandBox1和licenseType,它们将有共同的项目" email"将在哪个联接上进行

class sandBox1(models.Model):
    email = models.EmailField(unique=True)
    name = models.CharField(max_length=200)
    website = models.TextField(validators=[URLValidator()])
    comment = models.TextField(default='-')
    gender = models.CharField(max_length=6)
    def __str__(self):
        return self.email

class licenseType(models.Model):
    #1=other, 2=two-wheeler 4=four-wheeler
    licenseId = models.IntegerField()
    email = models.EmailField()

模板文件:index.html

<html><form id="form1" method="post" action="{% url "sandbox" %}">
   {% csrf_token %}
  Name: <input type="text" name="name" >
  <br><br>
  E-mail: <input type="text" name="email">
  <br><br>
  Website: <input type="text" name="website" >
  <span class="error"></span>
  <br><br>
  Comment: <textarea name="comment" rows="5" cols="40"></textarea>
  <br><br>
  Gender:
  <input type="radio" name="gender" value="female">Female
  <input type="radio" name="gender" value="male">Male
    <hr>Check the license type you have:-<br>
  <input type="checkbox" name="license[]" value=2 > 2 wheeler<br>
  <input type="checkbox" name="license[]" value=4 > 4 wheeler<br>
  <input type="checkbox" name="license[]" value=1 > Other <br>
  <br>
  <input type="submit" name="submit" value="Submit">
</form>
<div>
    {% for obj in sandBoxObj %}
        <p>
        {{ obj.name }}<br>
        {{ obj.email }}<br>
        {{ obj.website }}<br>
        {{ obj.gender }}<br>
        {{ obj.comment }}<br>
    {% endfor %}
</div>
</html>

这是一个需要更正的视图文件。我想显示这个SQL查询的结果:

select sandBox1.email,sandBox1.name,licenseType.licenseId from sandBox1 
innerjoin licenseType on sandBox1.email=licenseType.email;

查看档案

def sandbox(request):
template_name='domdom.html'
sandBoxObj = sandBox1.objects.all()
context = { 'sandBoxObj':sandBoxObj }
print request.POST
if request.method == 'POST':
    website=request.POST.get('website','')
    comment=request.POST.get('comment','')
    name=request.POST.get('name','')
    gender=request.POST.get('gender','')
    email=request.POST.get('email', '')
    license=request.POST.getlist('license[]')
    for id in license:
        licInst = licenseType(licenseId=id,email=email)
        licInst.save()
    sbinstance = sandBox1(website=website,comment=comment,name=name,gender=gender,email=email)
    sbinstance.save()

    return render(request,template_name,context)

2 个答案:

答案 0 :(得分:1)

原始sql方法/但我仍然对ORM方法感到困惑

def sandbox(request):
    template_name='domdom.html'
    sandBoxObj = sandBox1.objects.all()
    con = sqlite3.connect('/home/user1/PycharmProjects/djrest/invoicesproject/db.sqlite3')    #sqlite database file location
    cursor = con.cursor()
    cursor.execute(''' select todos_sandBox1.email,todos_sandBox1.name,todos_sandBox1.website,todos_sandBox1.comment,todos_sandBox1.gender,todos_licenseType.licenseId from todos_sandBox1 
join todos_licenseType on todos_sandBox1.email=todos_licenseType.email
 ''')  #it looks like django appends app name to table eg. appname = todos
    result = cursor.fetchall()
    #https://www.youtube.com/watch?v=VZMiDEUL0II
    context = { 'result':result }
    print request.POST
    if request.method == 'POST':
        website=request.POST.get('website','')
        comment=request.POST.get('comment','')
        name=request.POST.get('name','')
        gender=request.POST.get('gender','')
        email=request.POST.get('email', '')
        license=request.POST.getlist('license[]')
        for id in license:
            licInst = licenseType(licenseId=id,email=email)
            licInst.save()
        sbinstance = sandBox1(website=website,comment=comment,name=name,gender=gender,email=email)
        sbinstance.save()
    return render(request,template_name,context)

答案 1 :(得分:0)

很抱歉,如果这回答了错误的问题,但您可能需要考虑不同的数据模型/架构。您正在对SANDBOX1进行硬编码,这意味着可能存在多个沙盒,并且您列出了与User对象无关的电子邮件字段。一些基本的抽象可以简化工作。也许是这样的:

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

class LicenseTypes(models.Model):
    name = models.CharField(max_length=500)
class Customer(models.Model):
    name = models.CharField(max_length=500)
    license = models.ForeignKey(LicenseType)
class RegisteredUser(models.Model):
    customer = models.ForeignKey(Customer, on_delete = models.CASCADE)
    user = models.ForeignKey(User)

我更喜欢这种架构,因为它使用了更多本机django功能。并使连接真正基本。在视图中查看:

def django_view(request):
   registered_user = RegisteredUser(user=request.user)
   #example of how to use the join implicitly/ directly
   license = registered_user.customer.license.name