首页 > 解决方案 > Django Restframework 错误:获取属性错误和值错误

问题描述

使用 djangorestframework 和 djangorestframework-extensions 运行 Django 1.11 项目时出现以下错误:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/django/template/base.py", line 903, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [profile] in 'RackToSystem object'
Exception while resolving variable 'profile' in template 'customers/rack-detail.template.html'.
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/django/template/base.py", line 882, in _resolve_lookup
    current = current[bit]
TypeError: 'RackToSystem' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/django/template/base.py", line 890, in _resolve_lookup
    current = getattr(current, bit)
AttributeError: 'RackToSystem' object has no attribute 'profile'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/django/template/base.py", line 896, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'profile'

这是我的 serializers.py 代码:

class RackToSystemSerializer(serializers.ModelSerializer):
    rack_system = serializers.SerializerMethodField('add_sys_attrs')

    def add_sys_attrs(self, racktosystem):
        try:
            r = racktosystem.system.pk
        except Exception as nfe:
            print('System entry NOT FOUND! Check the DB for racktosystem entries that are orphaned.')
            print(nfe)
            return {}

        system  = {
            'serial':       racktosystem.system.serial.number,
            'status':       racktosystem.system.sys_status,
            'connections':  racktosystem.system.reconcile_net_connections(),
            'position':     racktosystem.rack_position,
            'reports_path': racktosystem.system.reports_path,
            'device_type':  'server',
            'hw_violations':[],
        }

        try:
            profiles_to_systems  = ProfileToSystem.objects.filter(system__pk = r).select_related()

            for record in profiles_to_systems:
                results = record.validate()

                if results:
                    system['hw_violations'].append(results)
        except Exception as E:
            pass

        try:
            system['address'] = racktosystem.system.discovery_set.all().order_by('-created').first().address
        except Exception as e:
            # log_it('Unable to determine IP address for serial "%s". It is probably a new system. Error was: %s' % (system['serial'],e))
            system['address'] = 'Unknown'

        return(system)

    class Meta:
        model  = RackToSystem
        fields = ('rack','rack_system')

这是我在models.py中的模型:

class RackToSystem (models.Model):
    rack          = models.ForeignKey(Rack, db_column="rack_id")
    system        = models.ForeignKey(System, db_column="system_id", unique=True)
    rack_position = models.IntegerField(db_column="rack_position")
    updated       = models.DateTimeField(db_column="updated", auto_now=True, null=True)
    created       = models.DateTimeField(db_column="created", auto_now_add=True, null=True)

    class Meta:
        db_table            = "customer_rack_to_system"        
        verbose_name        = "Rack-to-System"
        verbose_name_plural = "Racks-to-Systems"

    def __unicode__(self):
        return "%s [%s]" % (self.system, self.rack.name)

我们最近从 1.7.11 迁移到 Django 1.11 并升级到 drf-extensions 0.5.0。为解决问题所做的任何帮助将不胜感激。这在 Django 1.7.11 和 djangorestframework-extensions 0.0.3 中运行良好,但不适用于 drf-extensions。如果您需要任何其他详细信息,请告诉我。

标签: pythondjangodjango-rest-frameworkdrf-extensions

解决方案


推荐阅读