[英]Django retrieve data from multiple tables without foreign key relationship
我有以下三種型號
class Post(models.Model):
category_type = models.CharField(max_length=10)
participant_id = models.IntegerField()
title = models.CharField(max_length=200)
class Book(models.Model):
title = models.CharField(max_length=50)
author = models.CharField(max_length=500)
price = models.IntegerField(default=0)
class Instrument(models.Model):
title = models.CharField(max_length=50)
price = models.IntegerField(default=0)
在此,Post模型中的category_type可以是“ book”或“ instrument”,並且這些類別將來可能會增加。
Post表中的participant_id列基於category_type引用Book表或Instrument表的主鍵。
現在,我想從數據庫中檢索所有帖子和相關數據。
在MySql中,我可以這樣
select post.title,book.title from post,book where ((post.category_type="book" and post.participant_id=book.id))
union
select post.title,instrument.title from post,instrument where ((post.category_type="instrument" and post.participant_id=instrument.id))
但是我無法使用django做到這一點,因為我沒有外鍵關系。
非常感謝您的幫助。
更新:我通過修改Post表,嘗試使用Django的通用關系
class Post(models.Model):
category_type = models.CharField(max_length=10)
participant_id = models.PositiveIntegerField()
content_type = models.ForeignKey(ContentType)
participant_object = GenericForeignKey('content_type', 'participant_id')
title = models.CharField(max_length=200)
然后我發出以下查詢
Post.objects.filter(content_type=ContentType.objects.get_for_model(Book))
但這給我錯誤
FieldError: Cannot resolve keyword 'content_type' into field. Choices are: category_type, id, participant_id, title
如果無法在條件中指定數據,該如何檢索數據。
我使用了Timmy建議的Django的通用關系。 以下是Post的修改模型
class Post(models.Model):
category_type = models.CharField(max_length=10)
participant_id = models.PositiveIntegerField()
content_type = models.ForeignKey(ContentType)
participant_object = GenericForeignKey('content_type', 'participant_id')
title = models.CharField(max_length=200)
然后我發出以下查詢
Post.objects.filter(content_type=ContentType.objects.get_for_model(Book))
這給了我正確的結果。別忘了在修改模型后重建數據庫,否則會出錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.