kaminsky59
kaminsky59

Reputation: 95

Object has no attribute - HyperlinkedRelatedField

I am attempting to add hyperlinks to a list of "postings" that have a specific "category" ID

The URL that I am trying to build is for /categories/

models.py

class Categories(models.Model):
    ....
    idcategories = models.AutoField(db_column='idCategories', primary_key=True)

class Postings(models.Model):
    idpostings = models.AutoField(db_column='idPostings', primary_key=True)  # Field name made lowercase.
    idcategories = models.ForeignKey(Categories, db_column='idCategories')  # Field name made lowercase.
    ....

serializers.py

class CategorySerializer(serializers.HyperlinkedModelSerializer):
    postings = serializers.HyperlinkedRelatedField(many=True, view_name='postings-detail', read_only=True)

    class Meta:
        model = models.Categories
        fields = ('url', 'idcategories', 'categoriesname', 'categoryimageurl', 'postings')

views.py

url(r'postings/(?P<pk>[0-9]+)/$', postings_detail, name='postings-detail'),

I have the appropriate views set up, which work if I remove the HyperlinkedRelatedField on the CategorySerializer

Essentially I want:

JSON:
categoryname : <name>,
postings : [<list_of_postings>]

So with the above code, I get the following error:

AttributeError at /categories/ 'Categories' object has no attribute 'postings'

Upvotes: 2

Views: 1475

Answers (1)

Linovia
Linovia

Reputation: 20976

By default DRF will look at a related objects through the postings name which you don't have in your model.

Either set the idcategories related_name to "postings" or use the source serializer's field's argument source in the serializer's postings and set it to "postings_set".

Upvotes: 3

Related Questions