0

我有以下型号:

Class A(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    thumbnail = models.ImageField(...)

class B(models.Model)
   title = models.CharField()

   def save(*args, **kwargs):
     # Based on the title field I want to fetch some picture and then save the thumbnail in A

我有更多像 B 这样的类,应该从 A 引用(这就是我使用 GenericForeignKey 的原因)。我试图弄清楚的问题是当我save()在 B 中的方法中时如何保存缩略图字段(在 A 上)。在 A 中插入许多 if 语句以检查引用类的类型并相应地保存缩略图非常麻烦.

4

1 回答 1

0

查看文档,您可以从to添加反向通用关系BA

如果您知道最常使用哪些模型,您还可以添加“反向”通用关系以启用额外的 API

class A_Model(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    thumbnail = models.ImageField(...)

class B_Models(models.Model)
    title = models.CharField()
    a_models = generic.GenericRelation(A_Model)

现在你可以这样做:

 b = B_Model()
 a = A_Model(content_object=b, thumbnail=...)
 a.save()
 b.a_models.all() 
于 2013-10-11T11:08:35.833 回答