ericls / django-hashids

Non-intrusive hashids library for Django
MIT License
42 stars 10 forks source link

using with django rest framework #34

Open hosamhamdy258 opened 1 year ago

hosamhamdy258 commented 1 year ago

Could you explain how to use django-hashids with DRF correctly when trying to make post request consider this model and serialize files below

model.py

class  Author(models.Model):
    hashid = HashidsField()
    name = models.CharField(max_length=255)

class  Book(models.Model):
    hashid = HashidsField()
    name = models.CharField(max_length=255)
    author= models.ForeignKey(Author, on_delete=models.CASCADE)

serilizers.py

class  AuthorSerlizer(serializers.ModelSerializer):
    id = serializers.CharField(source="hashid", read_only=True)
    class  Meta:
        model = Author
        fields = "__all__"

class  BookSerlizer(serializers.ModelSerializer):
    id = serializers.CharField(source="hashid", read_only=True)
    author= serializers.PrimaryKeyRelatedField(
    pk_field=serializers.CharField(source="hashid"),
    queryset=Author.objects.all(),
    )
    class  Meta:
        model = Book
        fields = "__all__"

payload = {
"author":  "4JaYJV",
"name":  "book1"
}

this payload raises

"author":  ["Incorrect type. Expected pk value, received str."]}

Thanks in advance

mvanbaalen commented 1 year ago

I was able to get this working using DRF's SlugRelatedField

I added this to my model:

hashid = HashidsField(real_field_name="id")

And this to my viewset:

lookup_field = "hashid"

Finally, I changed my PrimaryKeyRelatedField on my Serializer to a SlugRelatedField:

post = SlugRelatedField(slug_field="hashid") # Whatever else you have