Django - 在创建或更新查询中使用模型字段部分

Spa*_*ain 6 python django django-models

给定 Django 2.2 应用程序中的以下模型:

class ShelfPosition(models.Model):
    shelf_code = models.CharField(max_length=10)
    row = models.IntegerField()
    column = models.IntegerField()

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=["shelf_number", "row", "column"], name="shelfpos_unique")
        ]

class Item(models.Model):
    name = models.CharField(max_length=255)
    position = models.OneToOneField(to=ShelfPosition, on_delete=models.SET_NULL, primary_key=True)
Run Code Online (Sandbox Code Playgroud)

我依靠 Django 的查找功能Item根据某些ShelfPosition字段过滤对象: Item.objects.filter(position__shelf_code="BF4")

在使用get_or_createor时,有什么方法可以实现类似的查找功能,例如上面描述的update_or_create

item, created = Item.objects.get_or_create(
    position__shelf_code="BF6",
    position__row=88,
    position__column=1,
    defaults={……}
)
Run Code Online (Sandbox Code Playgroud)

我发现它比以下内容更简洁,即使与此示例无关:

item, created = Item.objects.get_or_create(
    position = Position.objects.get_or_create(
        shelf_code="BF6",
        row=88,
        column=1
    ),
    defaults={……}
)
Run Code Online (Sandbox Code Playgroud)

Sim*_*tte 6

不确定这是您要找的,但如果您使用多表继承,您可以实现以下目标

class ShelfPosition(models.Model):
    shelf_code = models.CharField(max_length=10)
    row = models.IntegerField()
    column = models.IntegerField()

    class Meta:
        unique_together = ("shelf_code", "row", "column")

class Item(ShelfPosition):
    name = models.CharField(max_length=255)

item, created = Item.objects.get_or_create(
    shelf_code="BF6",
    row=88,
    column=1,
    defaults={
       "name": "Spam",
    }
)
Run Code Online (Sandbox Code Playgroud)

如果您想保留该行,您只需要确保keep_parents=True在调用时通过,item.delete()ShelfPosition因为默认的 MTI 行为是删除整个祖先链。