DRF tutorial 10- relationship field

https://www.django-rest-framework.org/api-guide/relations/

The core is the data structure in programming.

Relationship field used to indicate the relationship between the Model, such as foreign keys, M2M, O2O, as well as inverse relationship, custom relationships -GenericForeignKey

Relations.py field in the relation stated, when in use, may be used on their own serializers serialization class. <FieldName> referenced.

 

Use ModelSerializers class, will automatically generate a sequence of fields and relationships, we can examine these auto-generated field, and then to decide how to customize the relationship styles.

(Venv) E: \ the Python \ dj_test> Python manage.py the shell 
>>> from xxx.serializers Import ClothesSerializer 
>>> = ClothesSerializer Serializer () 
>>> Print (the repr (Serializer)) 
ClothesSerializer (): 
    URL = HyperlinkedIdentityField ( view_name = 'Clothes-Detail') 
    ID = IntegerField (label = 'ID', READ_ONLY = True) 
    Color = SlugRelatedField (QuerySet = <QuerySet that [<Colors: instance: Yellow>, <Colors: instance: Red>]>, slug_field = 'colors_cn') 
    desc = as CharField (MAX_LENGTH = 64) 
# use of the shell, the introduced sequence class, then instantiate and use the print function of this example repr object relation

  

API Reference

 To explain the relationship between a plurality of types of fields, as used herein, a few examples. Our model will be used for music albums Album, Track and track each album listed.

 

StringRelatedField

In the parent table, to give the sub-table model .__ str__ method returns the field. Because the corresponding sub-table is to-many relationship, so to add many = True

class ColorsSerializer(serializers.ModelSerializer):
    clothes = serializers.StringRelatedField(many=True)

    class Meta:
        model = Colors
        fields = ('url', 'id', 'colors', 'clothes')
--->
    {
        "url": "http://127.0.0.1:8002/colors/1/",
        "id": 1,
        "colors": "yellow",
        "clothes": [
            "内衣一号",
            "内衣二号"
        ]
    }

  

  

 

Guess you like

Origin www.cnblogs.com/jabbok/p/11313851.html