手动选择数据库时的Django Generic Relation

时间:2015-12-31 17:16:05

标签: python django

我在#((?:www\.)?(?:youtube\.com\/(?:watch\?v=|embed\/ )|youtu\.be\/ )([a-zA-Z0-9-]*))#i #((?:www\.)?(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/|youtube\-nocookie\.com\/embed\/)([a-zA-Z0-9-]*))#i 中使用了genericrelation

project1

如果我在project1中,

class Sale(models.Model):
    id = models.AutoField(primary_key=True)
    invoice = GenericRelation('Invoice')

class Invoice(models.Model):
    id = models.AutoField(primary_key=True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

我使用inspectdb命令在>>>sale = Sale.objects.all() >>>sale[0].invoice.all() [<Invoice: 155>] 下的应用中收集了所有模型。 但如果我在其他project2中重复相同的话。我正在使用using关键字手动选择数据库,我收到错误。

Models.py包含Invoice模型,

project2

我执行相同的代码,

class AppInvoice(models.Model):
    id = models.IntegerField(primary_key=True)  # AutoField?

    object_id = models.IntegerField()
    content_type = models.ForeignKey(DjangoContentType)

    class Meta:
        managed = False
        db_table = 'app_invoice'

class AppSale(models.Model):
    id = models.IntegerField(primary_key=True)  # AutoField?

    class Meta:
        managed = False
        db_table = 'app_sale'

如何在project2中访问销售发票?

1 个答案:

答案 0 :(得分:0)

  1. Invoice模型包含content_typeobject_id
  2. content_type是fk到DjangoContentType型号。 object_id是正数,实际上是Sale模型的id。
  3. DjangoContentType包含属性idmodelnameapp_label
  4. 结合这3个我得到了相关销售的发票,

    sale = AppSale.objects.using('project1').all()
    content = DjangoContentType.objects.using('project1').get(model='sale')
    invoice = AppInvoice.objects.using('project1').filter(content_type=content,object_id=sale[0].id)
    [<AppInvoice: AppInvoice object>]