【问题标题】:Django retrieve data from multiple tables without foreign key relationshipDjango从没有外键关系的多个表中检索数据
【发布时间】:2014-11-07 13:05:53
【问题描述】:

我有以下三个模型

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 可以是“书”或“仪器”,这些类别将来可以增加。

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

如果无法在条件中指定数据,如何检索数据。

【问题讨论】:

  • 您可能对Django's generic relations 感兴趣,它允许您在不同模型之间创建关系
  • 嗨,蒂米,我尝试使用 Django 的通用关系,但使用它我无法检索结果。只有当我事先知道特定的书籍对象时,它才有用。但我不知道如何使用这种通用关系检索数据
  • 这个错误看起来你没有重建数据库
  • 是的,这就是问题所在。我删除了表并做了syncdb,上面提到的方法奏效了。

标签: python mysql django orm


【解决方案1】:

我按照 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))

这给了我正确的结果 修改模型后不要忘记重建数据库,否则会出错。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    相关资源
    最近更新 更多