简体   繁体   中英

How serialize a DRF model class name?

I've been given an example JSON output which I must reproduce uisng Django Rest Framework.

Ths is the output:

"results": [
    {
      "Brand": [
        {
          "BrandName": "20/20",
          "Store": [
            {
              "ID": "4",
              "User": [
                "1"
              ],
         etc

How do I Model this in DRF?

Can this be done or have a missed something with models?

You should pass many=True into Storeserializer

class BrandSerializer(serializers.ModelSerializer):
    stores = Storeserializer(many=True)
    class Meta:
        """ Serializer configuration. """
        model = Brand
        fields = ("BrandName", "stores")

Also, if you get some troubles with field naming, you can use source parameter:

class SomeModel(...):
    some_field = models.CharField(...)  # pythonic snake_case


class SomeClassSerializer(...):
    class Meta:
        model = SomeModel
        fields = (“SomeField”,)
    SomeField = serializers.CharField(source=“some_field”)  # CamelCase if it needed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM