0

I'm trying to reverse a foreign key relationship from one model to the another. In my case, that means seeing all Groups objects (many) for a given FieldFacet object (one).

I've tried using field_object.groups_set method as described here, but i get the error:

AttributeError: 'FieldFacet' object has no attribute 'groups_set'

I have checked that (as is the accepted solution) I am importing the objects, and that i can refer to them bu name, and query their objects.

My models look like this:

class FieldBase(models.Model):
    field = models.ForeignKey('Field', on_delete=models.CASCADE)
    ...
    class Meta:
        abstract = True
class FieldFacet(FieldBase):
    ...

class Groups(models.Model):
    field = models.ForeignKey('FieldFacet', related_name='facet_field', on_delete=models.CASCADE)
    ...

ff = FieldFacet.objects.get(pk=1)
ff.__dict__
# output
# {'_state': <django.db.models.base.ModelState object at 0x7fa22b9865c0>, 'id': 1, 'recipe_id': 1, 'field_id': 1, 'data_type': 'text', 'json_path': '_id', 'order': 0, 'normalization': True, 'stripping': True, 'intelligent_size_limit': 0, 'max_values': 10, 'sorting': 'count', 'groups': 'no', 'default_group': ''}

gg = Groups.objects.all()
for g in gg:
    print(g.__dict__)
# output
# {'_state': <django.db.models.base.ModelState object at 0x7fa22b986b38>, 'id': 4, 'field_id': 1, 'name': 'p', 'minimum': None, 'maximum': None, 'values': '7'}
# {'_state': <django.db.models.base.ModelState object at 0x7fa22b986ba8>, 'id': 3, 'field_id': 1, 'name': 'second', 'minimum': 1, 'maximum': 3, 'values': None}
# {'_state': <django.db.models.base.ModelState object at 0x7fa22b986c18>, 'id': 2, 'field_id': 1, 'name': 'text', 'minimum': None, 'maximum': None, 'values': 'list of text'}
# {'_state': <django.db.models.base.ModelState object at 0x7fa22b986c88>, 'id': 1, 'field_id': 1, 'name': 'first', 'minimum': 5, 'maximum': 10, 'values': None}

# problem here:
gro = ff.groups_set
# Traceback (most recent call last):
# File "<console>", line 1, in <module>
# AttributeError: 'FieldFacet' object has no attribute 'groups_set'

Why am i seeing this error?

Preston
  • 7,399
  • 8
  • 54
  • 84

2 Answers2

1

You have set related_name on the ForeignKey. Try ff.facet_field.all()

Daniel Hepper
  • 28,981
  • 10
  • 72
  • 75
1

You gave field 'field' the name facet_field. try ff.facet_field and you will get what you are looking for.