首页 > 解决方案 > 如何获取延迟属性值?

问题描述

我需要比较两个 ID 值以查看它们是否匹配。在这个数据库中,其中有区域和位置。我需要检查某个区域中的哪些位置。区域有一个 ID 作为主键,位置有一个指向区域的外键。

    if obj.area.id == self.id:

出于某种原因,外键总是返回正确的值,而 self.id (在 Area 类中)总是返回<django.db.models.query_utils.DeferredAttribute object at 0x03506B70>. 我已经尝试过 Area.id、Area.pk、Area._get_pk_val 以及使用 self 而不是 Area 的所有内容。如何从延迟属性中提取值?

    class Area(models.Model):
        id = models.IntegerField(default=0, primary_key=True)
        name = models.CharField(max_length=30)
        longitude = models.FloatField(default=0)
        latitude = models.FloatField(default=0)

        def __str__(self):
            return self.name

        def number_of_locations(self):
            count=0
            measurements.objects
            for obj in Location.objects.all():
                print (str(obj.area.id)+" vs "+str(self.id))
                if obj.area.id == self.id:
                    print("check")
                    count+=1
            return count

编辑:终于让它工作了。现在它检查所有区域而不是当前所在的区域,并返回所有位置数量的数组。这不是我最初的意图,但它会起作用。

        def number_of_locations(self):
        count_array = []
        count=0
        for a in Area.objects.all():
            for obj in Location.objects.all():
                #print (str(obj.area.id)+" vs "+str(a.id))
                if obj.area.id == a.id:
                    print("check")
                    count+=1
            count_array.append(count)
            count=0
        return count_array

标签: pythondjango

解决方案


您可以通过exists(). 如果模型中存在此项目,它将返回 true 试试这个

def number_of_locations(self):
    count = 0
    for obj in Location.objects.all():
        print(str(obj.area.id) + " vs " + str(self.id))
        if obj.area.id == Area.objects.filter(pk=obj.area.id).values_list('pk', flat=True).first():
            print("check")
            count += 1
    return count

推荐阅读