djongo icon indicating copy to clipboard operation
djongo copied to clipboard

<Bug> raising AttributeError when trying add new reference to ArrayReferenceField

Open alihoseiny opened this issue 8 years ago • 3 comments

AttributeError will raise when trying to add new reference to ArrayReferenceField gotten from queryset

Python script

Models:

    class ChildModel(models.Model):
        name = models.TextField(max_length=32)


    class ParentModel(models.Model):

        name = models.TextField(max_length=32)
        childs = models.ArrayReferenceField(ChildModel, on_delete=models.DO_NOTHING, blank=True, null=True)

Codes tried in shell:

aa = ParentModel.objects.filter(id=9).first()
aa.childs.add(ChildModel.objects.get(id=4))

This code raises following exception:

lib/python3.6/site-packages/djongo/models/fields.py", line 750, in add
    fks.update(new_fks)
AttributeError: 'list' object has no attribute 'update'

But if works when we create model for the first time:

a = ParentModel.objects.create(name="test5")
 b = ChildModel.objects.get(id=1)
c = ChildModel.objects.get(id=2)
d = ParentModel.objects.get(id=9)

alihoseiny avatar Sep 04 '18 09:09 alihoseiny

I think you are not using the latest version on Djongo. Because, to python will always ensure that authors read from the db, will be a set:

def to_python(self, value):
    if value is None:
        return set()
    return set(value)

Please check if this is applicable with latest HEAD of master

nesdis avatar Sep 04 '18 18:09 nesdis

Using 1.2.30. I am observing the same issue

jlouis12 avatar Oct 10 '18 02:10 jlouis12

The same happened to me, but managed to fix it. The problem was i was initiating the field with a default=[] parameter, so thats why it tries to apply .update to a list.

Remember that a ArrayReferenceField is treated like a ManyToMany field so null=True, blank=True or a empty default parameters is redundant for this field because it always start empty, so this behaviour shouldn't be specified in the field parameters.

So the fixed code it's:

class ChildModel(models.Model):
    name = models.TextField(max_length=32)


class ParentModel(models.Model):
    name = models.TextField(max_length=32)
    childs = models.ArrayReferenceField(ChildModel, on_delete=models.DO_NOTHING)

Vichoko avatar Aug 10 '19 03:08 Vichoko