Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework Many=False producing errors

I am stuck on trying to solve an issue with the Serializers and related fields using the django-rest-framework. Currently I have a model that looks like this:

class DataSetModel(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()

class DataPointModel(models.Model):
    dataSet = models.ForeignKey(DataSetModel, related_name='dataPoints')
    label = models.CharField(max_length=200)

My serializers look like this:

class DataPointSerializer(serializers.ModelSerializer):
    class Meta:
        model = DataPointModel
        fields = ('pk','label')

class DataSetSerializer(serializers.ModelSerializer):
    dataPoints = DataPointSerializer(many=True, read_only=True)

    class Meta:
        model = DataSetModel
        fields = ('pk','title')

The problem I am having is when I try to change the "many=False" in the serializer produces this error:

Got AttributeError when attempting to get a value for field label on serializer DataPointSerializer. The serializer field might be named incorrectly and not match any attribute or key on the RelatedManager instance. Original exception text was: 'RelatedManager' object has no attribute 'label'.

Since this is only ever one model object (one-to-many relationship), I want to get the result as a single object vs a list of one object.

Am I doing this the right way? I thought that turning the "many=False" it would fetch the first record in an nested query.

Any insight would be greatly appreciated.

like image 941
renderbox Avatar asked Oct 24 '25 14:10

renderbox


2 Answers

You can't set many=False, because dataPoints is a related field that returns a queryset containing a list of instances, not just an instance.

When you do DataPointModel.dataPoints that returns a queryset, it can't returns just an instance. So setting many=False, it wouldn't get the first element of the list.

like image 167
levi Avatar answered Oct 26 '25 03:10

levi


So the solve I came to was refactoring my models with where the Foreign Keys are attached.

Here is the fix I implemented:

class DataSetModel(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    dataPoint = models.ForeignKey(DataPointModel)

class DataPointModel(models.Model):
    label = models.CharField(max_length=200)

Moving it to the DataSetModel automatically joins the data model if you set 'many=False' in the Serializer object.

like image 43
renderbox Avatar answered Oct 26 '25 03:10

renderbox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!