保存带有外键引用的序列化程序时,Django无法运行

时间:2019-01-15 21:09:10

标签: python django django-models django-rest-framework django-serializer

因此,我有一个带有一个外键引用的模型,该模型工作了好几个星期。我最终不得不向模型添加另一个外键引用,但现在我无法使用序列化器保存任何记录。我应该提到我正在使用Django 2.1。 这是我正在使用的模型(为简单起见,删除了一些字段):

class Finding(models.Model):
    finding_id = models.IntegerField(null=False, blank=False, primary_key=True, db_index=True)
    name = models.CharField(null=True, blank=True, max_length=255)
    web_app = models.ForeignKey(WebApplication, on_delete=models.CASCADE)
    q_id = models.ForeignKey(StagingQkb, on_delete=models.CASCADE)

新的FK是q_id字段。以前只是一个普通的int。我实际上已经吹走了旧表,而新表仍然是完全空的,因此我知道现有数据不是问题(带有外键的表仍然完好无损)。在以前保存Findings时,我只需为“ web_app”提供WebApplication对象的PK。据我所知,这仍然有效。当以相同方式插入“ q_id”字段时,它抱怨它需要一个int / string / bytes而不是StagingQkb对象。好吧,我没有给它一个StagingQkb对象,所以有什么用!

这是序列化器:

class FindingSerializer(serializers.ModelSerializer):

    class Meta:
        model = Finding
        fields = '__all__'

我要提供给序列化程序的数据如下:

data = {'finding_id': 5514989,
        'name': 'Sample-Name',
        'q_id': 12345,
        'web_app': 67890}

当我将数据插入序列化程序时,我正在执行以下操作:

>>> fs = FindingSerializer(data=data)
>>> fs.is_valid()
True
>>> fs.save()

运行以上代码后出现的错误如下:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/opt/oss/python35/lib/python3.5/site-packages/rest_framework/serializers.py", line 214, in save
    self.instance = self.create(validated_data)
  File "/opt/oss/python35/lib/python3.5/site-packages/rest_framework/serializers.py", line 959, in create
    raise TypeError(msg)
TypeError: Got a `TypeError` when calling `Finding.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Finding.objects.create()`. You may need to make the field read-only, or override the FindingSerializer.create() method to handle this correctly.
Original exception was:
 Traceback (most recent call last):
  File "/opt/oss/python35/lib/python3.5/site-packages/rest_framework/serializers.py", line 940, in create
    instance = ModelClass._default_manager.create(**validated_data)
  File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/query.py", line 413, in create
    obj.save(force_insert=True, using=self.db)
  File "/home/dpz3w0q/AutonomousPrimeD/autonomousprimed/Finding/models.py", line 83, in save
    q_id=self.q_id)
  File "/home/dpz3w0q/AutonomousPrimeD/autonomousprimed/Finding/models.py", line 173, in evaluate
    if ScoreMatrix.objects.filter(q_id=q_id).count() > 0:
  File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/query.py", line 844, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/query.py", line 862, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1263, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1287, in _add_q
    split_subq=split_subq,
  File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1225, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1096, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/lookups.py", line 20, in __init__
    self.rhs = self.get_prep_lookup()
  File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/lookups.py", line 70, in get_prep_lookup
    return self.lhs.output_field.get_prep_value(self.rhs)
  File "/opt/oss/python35/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1807, in get_prep_value
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'StagingQkb'

我完全被困在这里。我没有改变将数据传递给序列化器的方式,因此我真的无法分辨自己做错了什么。如果有人能够帮助我完成这项工作,我将不胜感激!

1 个答案:

答案 0 :(得分:0)

由于@WillKeeling,我意识到我在save()方法中有一个对Finding.q_id的引用,在进行FK更改后我忘记了对其进行更新。外部表的PK是qkb_id,因此我更改了对Finding.q_id.qkb_id的引用,因此能够保存模型。