Django两桌联合

时间:2017-03-16 17:04:54

标签: python sql-server django

我使用$ python manage.py inspectdb从MSSQL获取以下表格,图书表格可能有很多图片,所以我查看其forignkey的 Mpeg 表格。< / p>

如何获取mpeg信息 foreignkey = book_id

model.py

class Book(models.Model):
    book_id = models.AutoField(db_column='book_id', primary_key=True)  # Field name made lowercase.
    book_name = models.CharField(db_column='book_name', max_length=100, blank=True, null=True)  # Field name made lowercase.   
    media = models.CharField(max_length=200, blank=True, null=True)
    class Meta:
        db_table = 'book'

class Mpeg(models.Model):
    picture_id = models.AutoField(primary_key=True)
    picture_name = models.CharField(max_length=50)
    picture_type = models.CharField(max_length=50)
    picture_url = models.CharField(max_length=100)
    foreignkey = models.IntegerField(db_column='foreignKey')  # Field name made lowercase.
    class Meta:
        db_table = 'mpeg'

views.py

def map_player_post(request, book_id):
    book = models.Book.objects.get(book_id = book_id)
    mpeg = models.Mpeg.objects.all() #Tried filter but failed
    template = get_template('map.html')
    request_context = RequestContext(request)
    request_context.push(locals())
    if book != None:
        html = template.render(request_context)
        return HttpResponse(html)

模板

<h4>{{book.mpeg.count}}</h4> //get the book count

1 个答案:

答案 0 :(得分:0)

  

Book表可能有很多图片

为了实现这一目标,您必须在Mpeg模型中使用ForeignKey,如下所示:

class Mpeg(models.Model):
    picture_id = models.AutoField(primary_key=True)
    picture_name = models.CharField(max_length=50)
    picture_type = models.CharField(max_length=50)
    picture_url = models.CharField(max_length=100)
    book = models.ForeignKey('Book', models.CASCADE)
    # remove the foreignkey = models.IntegerField(db_column='foreignKey')

    class Meta:
        db_table = 'mpeg'

现在运行./manage.py makemigrations./manage.py migrate,然后(当然,在填写一些数据之后),您可以执行以下查询:

book = Book.objects.get(book_id=book_id)
mpeg = Mpeg.objects.filter(book=book)

[BONUS]:您可以删除picture_idbook_id字段,因为Django会自动为您添加id。然后你可以重写上面这样的表达式:

book = Book.objects.get(id=book_id)
mpeg = Mpeg.objects.filter(book=book)