python - 是否检查相关对象

标签 python django postgresql django-models

我需要检查我的对象是否相关ORM postgresql/

我有两个对象 ItemVariationValue 和 ItemVariation 我需要检查 ItemVariationValueItemVariation

有关系

模型.py

class ItemVariation(models.Model):
    item=models.ForeignKey(Item,on_delete=models.CASCADE)
    price=models.IntegerField(blank=True,null=True,default=0)
    item_code=models.CharField(max_length=500)
    keywords= models.ManyToManyField(Keyword)
    image=models.ImageField(upload_to='dishes/', blank=True, null=True)
    def __str__(self):
        return str(self.id)

class ItemVariationValue(models.Model):
    item=models.ForeignKey(Item,on_delete=models.CASCADE)
    item_variation=models.ForeignKey(ItemVariation,on_delete=models.CASCADE)
    attribute=models.ForeignKey(Attribute,on_delete=models.CASCADE)
    attribute_value=models.ForeignKey(AttributeValue,on_delete=models.CASCADE)
    def __str__(self):
        return str(self.id)

views.py

def get_items(request):    # request= {"order_details": "varxxx:1"}
    order=request.data['order_details']
    items = order.split(',')
    total = 0
    for item in items:
        od = item.split(':')
        sku = str(od[0])
        qty = int(od[1])
        itemvariation=ItemVariation.objects.get(item_code=sku)



# if ItemVariationValue.item_variation has ForeignKey(ItemVariation):

最佳答案

Note (ForeignKey nomenclature): ForeignKeys should not have an _id suffix, since Django will automatically construct an extra field fieldname_id that contains the primary key. By writing an _id suffix, you will introduce extra attributes like item_variation_id_id. Although strictly speaking that is not a problem, it introduces a lot of confusion. For example my_itemvariationvalue.itemvariation_id will result in an ItemVariation object, etc.

如果您修复了 ForeignKey 名称,您可以这样检查:

# given the ForeignKey is named itemvariation, not itemvariation_id and use Comparison Operators 

if my_itemvariationvalue.itemvariation_id == my_itemvariation.id:
    # ... (objects are related)
else:
    # ... (otherwise)

通过在此处使用 itemvariation_id,我们避免加载相关对象,从而避免潜在的额外数据库查询。

关于python - 是否检查相关对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52423510/

相关文章:

django - 在基本模板 Django Python 中从数据库获取数据

python - 从 django-admin 中选择另一个外键来过滤外键字段?

SQL 行到列值

postgresql - Postgres 查询 : array_to_string with empty values

django - 用于捕获 URL 中所有文件夹(包括正斜杠)的正则表达式模式

postgresql - 如何升级 Postgres93.app

python - 如果某个时间在某个时间范围内,则查找该时间并返回 Pandas 中的相应值?

python - 如何在 Ubuntu 上安装当前的 OpenPYXL 包

python - 如何在 moviepy 中使用 png 蒙版?

python - 将两个 pandas DataFrame 与一个唯一的列组合起来,并保留行索引 (Python)