gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:15:36 25 4
gpt4 key购买 nike

给定 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)

我依靠 Django 的查找功能来过滤 Item对象取决于某些 ShelfPosition领域: Item.objects.filter(position__shelf_code="BF4")
在使用 get_or_create 时,有什么方法可以实现如上所述的类似查找功能吗?或 update_or_create ?
item, created = Item.objects.get_or_create(
position__shelf_code="BF6",
position__row=88,
position__column=1,
defaults={……}
)

我发现它没有以下内容那么冗长,即使在这个例子中它并不真正相关:
item, created = Item.objects.get_or_create(
position = Position.objects.get_or_create(
shelf_code="BF6",
row=88,
column=1
),
defaults={……}
)

最佳答案

不确定这是您要查找的内容,但如果您使用了 multi-table inheritance您可以实现以下目标

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",
}
)

你只需要 make sure to pass keep_parents=True when calling item.delete() 如果你想保留 ShelfPosition row 作为默认的 MTI 行为是删除整个祖先链。

关于python - Django - 在创建或更新查询中使用模型字段部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60967795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com