python - 获取 Django 模型所有相关的通用记录
问题描述
我有一个带有 的 Django 模型GenericForeignKey
,还有几个其他模型指向它GenericRelation
:
class InventoryAction(CustomModel):
action_content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT,limit_choices_to={'model__in': ('inventoryinput', 'inventorytransfer', 'inventoryadjustment', 'physicalinventory', 'requisition', 'sale', 'inventorysalecancellation', 'inventorystockinit')}, related_name='inventory_actions', verbose_name=_("Tipo de Acción"))
action_object_id = models.PositiveIntegerField(verbose_name=_("ID de la acción"))
action_object = GenericForeignKey('action_content_type', 'action_object_id')
timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Fecha y hora"))
class InventoryStockInit(CustomModel):
repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='stock_init', verbose_name=_("Almacén"))
timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Fecha y Hora"))
comments = models.TextField(null=True, blank=True, verbose_name=_("Comentarios"))
inventory_action = GenericRelation(InventoryAction, content_type_field='action_content_type', object_id_field='action_object_id')
class InventoryInput(CustomModel):
repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='inputs', verbose_name=_("Almacén"))
reference = models.ForeignKey(InventoryAction, null=True, blank=True, on_delete=models.PROTECT, limit_choices_to=Q(action_content_type__model__in=['inventorytransfer', ]), related_name='referenced_by', verbose_name=_("Referencia"))
inventory_action = GenericRelation(InventoryAction, content_type_field='action_content_type', object_id_field='action_object_id')
我有一个 Django Rest Framework 视图集,它试图从 GenericForeignKey 获取所有相关记录:
class InventoryActionForListViewSet(viewsets.ViewSet):
permission_classes = (permissions.IsAuthenticated,)
def list(self, request):
self.repository = request.query_params['repository']
inventory_actions = models.InventoryAction.objects.filter(inventory_action__repository_id=self.repository).order_by('-timestamp')
inventory_actions_to_return = serializers.InventoryActionForListSerializer(inventory_actions, many=True)
return Response(inventory_actions_to_return)
问题是视图引发了以下异常:
django.core.exceptions.FieldError: Cannot resolve keyword 'inventory_action' into field. Choices are: action_content_type, action_content_type_id, action_object, action_object_id, batch, id, products, referenced_by, referenced_by_input_or_output, referenced_by_output, timestamp
我可以看到GenericRelation
没有被识别。如何使用通用关系执行我想要的查询?
解决方案
inventory_action
是您的 InventoryStockInit 和 InventoryInput 模型中的一个字段 - 您不能期望它是您的 InventoryAction 模型中的一个字段。
使用您定义的关系,您的每个 InventoryAction 对象都可以与 中所述的其中一个模型中的单个对象相关联limit_choices_to
。只有一个对象与单个 InventoryAction 相关。您可以通过访问来访问它action object
,例如:
inventory_action = InventoryAction.objects.first()
inventory_action.action_object # this will be a single object of one of the models in limit_choices_to.
InventoryInput
另一方面,您的模型可以通过多个库存操作来指向。要查看哪些库存操作指向特定的 InventoryInput 对象,您可以执行以下操作:
inventory_input = InventoryInput.objects.first()
inventory_input.inventory_action.all()
如您所见,inventory_action
是所有相关对象的管理器,最好称它为inventory_actions
(复数)。我认为您可能想要实现的是反向关系(其他模型的多个对象引用的单个 InventoryAction 对象)。
推荐阅读
- javascript - Selenium:如何编写同步 Selenium 自动化?
- ios - SWIFT SpriteKit:如何使用 SKnode 的 userData 属性来减少其中的键值?
- python - ESRI 层显示在一台机器上而不是另一台机器上
- iis - web.config 多个域别名,一个 IIS VHOST 中的两个站点。啊啊啊啊
- python - Matplotlib 饼图自动百分比不起作用
- variables - 文件名的一部分作为变量
- c# - 有没有办法用匿名方法配置这个 Task.WhenAll Select ?
- postgresql - 如何从字符串中提取特定数字数量并使用 postgres 添加它们
- java - 另一个程序使用的文件尝试移动文件时出错 - Java 8 - 已关闭
- java - 画布未绘制到 JFrame