How to get a query set for SlugRelatedField on the model?

1,205 views
Skip to first unread message

Chris Foresman

unread,
Jun 25, 2015, 12:33:13 PM6/25/15
to django-res...@googlegroups.com
I'm not even sure how to write this question, but I want a writeable SlugRelatedField on a ModelSerializer. (http://tomchristie.github.io/rest-framework-2-docs/api-guide/relations#slugrelatedfield) The queryset needs to be filtered for the value on another field of the Model. Is this even possible?

Here's some sample code to try and explain:

class MyModel(models.Model):
    name
= models.CharField()
    thing1
= models.ForeignKey(MyModel2)
    thing2
= models.ForeignKey(MyModel3)


class MyModel2(modles.Model):
    name
= models.CharField()
    address
= models.CharField()
    phone
= models.CharField()


class MyModel3(models.Model):
    name
= models.CharField()
    value
= models.DecimalField()
    related
= ForeignKey(MyModel2)




class MyModelSerializer(serializers.ModelSerializer):
    thing2
= serializers.SlugRelatedField(slug_field='name', required=False, queryset=???)



I think I want object.thing1.mymodel3_set.all(), because I only want to choose from objects that match on the slug_field and related=object.thing1.

Chris Foresman

unread,
Jun 25, 2015, 1:27:16 PM6/25/15
to django-res...@googlegroups.com
I tried making it a method on the serializer, like so:
def get_queryset(self):
   
return self.object.thing1.mymodel3_set.all()


That didn't work.

Tom Christie

unread,
Jun 26, 2015, 11:21:34 AM6/26/15
to django-res...@googlegroups.com, fore...@gmail.com
Maybe use a standard SlugRelatedField, but include some multi-field validation in the serializer.validate() method?
(The available options wouldn't be filtered in the browsable API, but it'd let you do the validation you're after, right?)

Chris Foresman

unread,
Jun 26, 2015, 11:39:32 AM6/26/15
to django-res...@googlegroups.com
The real trick wasn’t the validation, but writing a queryset that would work for the field. What we ended up doing was using a CharField and using some custom logic in the update method. We already have some other custom attribute setting going on in update that this was the quickest fix that worked.

Thanks!




On Jun 26, 2015, at 10:21 AM, Tom Christie <christ...@gmail.com> wrote:

Maybe use a standard SlugRelatedField, but include some multi-field validation in the serializer.validate() method?
(The available options wouldn't be filtered in the browsable API, but it'd let you do the validation you're after, right?)

--
You received this message because you are subscribed to a topic in the Google Groups "Django REST framework" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-rest-framework/xm8KkL3Vjnc/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages