2

Sorry if this is a repeat, I tried searching for this with no luck.

I would like to know, how to specify a lookup field for a related model.

For example I have models related using a foreign key like so

class Quiz(models.Model):                                                                                      
    guid = models.CharField(max_length=11, unique=True, blank=True)

class Result(models.Model):
    guid = models.CharField(max_length=11, unique=True, blank=True)
    quiz = models.ForeignKey(Quiz)

Here I use guid as my unique identifier and I have my model serializers as below.

class QuizSerializer(serializers.ModelSerializer):                                                                                 
    results = ResultSerializer(many=True, required=False)

    class Meta:
        model = Quiz
        fields = ('guid', 'results')

class ResultSerializer(serializers.ModelSerializer):
    #lookup_field = 'guid' => Does not seem to work??

    class Meta:
        model = BroncoResult
        fields = ('guid',)

In the view I use viewsets.ModelViewSet

class QuizViewSet(viewsets.ModelViewSet):                                                                                          
    queryset = Quiz.objects.all()
    serializer_class = QuizSerializer
    lookup_field = 'guid'

Which returns data like this {"guid": "12312312312", "results": [{"guid": "45645645666"}, {"guid": "78978978999"}]}

I can specify the lookup field be guid for the Quiz model, in the QuizViewSet but how can I specify the lookup field be guid for the Result model in the serializer?

I seem to be getting the following error on a PUT request {"results": [{"guid": ["Result with this Guid already exists."]} which I think is because it is trying to retrieve the record by id and not finding it, and throwing the error because it tries to create a new record with the same unique guid.

Any body know how to specify that the result field use guid as the lookup as well?

Thanks for your help.

akotian
  • 3,885
  • 1
  • 33
  • 44
  • 4
    Instead of `lookup_field = 'guid'`, try with `lookup_field = 'result__guid'`. Here is a [similar question](http://stackoverflow.com/questions/29068097/django-rest-framework-lookup-field-through-onetoonefield/29073607#29073607). – Todor May 23 '15 at 06:04

0 Answers0