我使用$ 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
答案 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_id
和book_id
字段,因为Django会自动为您添加id
。然后你可以重写上面这样的表达式:
book = Book.objects.get(id=book_id)
mpeg = Mpeg.objects.filter(book=book)