Search code examples
pythondjangoweb-servicesrestrestful-architecture

Django Choice field best practice in web services


class Book(models.Model):

    CATEGORY = (
        (1, "Sci-Fi"),
        (2, "Romance"),
        (3, "Fantasy"),
        # more categories...
    )

    title = models.CharField(max_length=255)
    cat = models.IntegerField(choices=CATRGORY, null=True, blank=True)
    author = models.ManyTboManyField('User', related_name="book")

This is my model. What I want is how do/should I send response data, I mean format.(JSON)

for e.g.(response for a book)

{"author": [1,3,4], "title": "my book", "cat": 1, 'bookid': 23 } 

or

{"author": [1,3,4], "title": "my book", "cat": "Sci-Fi", 'bookid': 23 }  #slugify name

the problem from 1st type is that I have to maintain this tuple/mapping in frontend as-well (for end user visualization) and id for internal mapping, api-DB interaction.

from 2nd type I dont know how would I map if some api post/put some data to my system, I wont know which id this category belong to.

I need suggestion from people like you who have rich experience in web service development and can guide me to develop APIs in best possible way and this could be helpful for future readers who are newbie or learning things.


Solution

  • Personally I would prefer both to be present in the API response, something like:

    {"author": [1,3,4], "title": "my book", "cat_id": 1, "cat_name": "Sci-Fi"} 
    

    reason being, just the id doesn't impart much information by itself about the category, and the name is something variable in the future, so that alone doesn't help either.

    Of course, with both present, we can specify in the documentation that the cat_name is for cosmetic purpose, while the cat_id is what will remain same.