Service requirements: When we query a sub-table, we want to obtain the data of the primary table associated with the sub-table, or we need to query the data of all the records of a sub-table corresponding to the primary table. Function split:

  1. Create a subtable Comment that has the foreign key associated with the primary table and query the primary table associated with the subtable.
class Comment(models.Model) : "" "product_id: Corresponding commodityid
        p_comment_id: Corresponding evaluation during the additional evaluationid
        info: Evaluation textu_id: comment on personid"" "def __str__(self) :return self.info
    class Meta:
        verbose_name = "Evaluation"
        verbose_name_plural = verbose_name
    product_id = models.IntegerField(default=0)
    p_comment_id = models.IntegerField(default=0)
    info = models.CharField(max_length=500)
    u_id = models.IntegerField(default=0)
    good = models.ForeignKey(Good,on_delete=CASCADE,default=0)
    create_time = models.DateTimeField(default=datetime.datetime.now())
    create_name = models.CharField(max_length=20)
    update_time = models.DateTimeField(default=datetime.datetime.now())
    update_name = models.CharField(max_length=20)
    is_delete = models.IntegerField(default=0) # logical delete0normal1: deleteCopy the code

Create a foreign key field named GOOD in the child table associated with the primary key of the primary table:

 good = models.ForeignKey(Good,on_delete=CASCADE,default=0)
Copy the code

On_delete =CASCADE When a primary table record is deleted, all subtables with foreign keys associated with the record are deleted simultaneously

perform

1. python3 manage.py makemigrations
2. python3 manage.py migrate
Copy the code

Generate a foreign key field in the database as follows:

Create some mock data, and then execute a subtable query that returns the following result

In this case, the foreign key field displays the ID of the primary key of a primary table rather than the specific information. If we want the child table query to return the details of the primary table, we can sit down and change it at serialization time:

# Evaluate serialized classesclass CommentSerializer(serializers.ModelSerializer) :class Meta: # forGoodSerializemodel = Comment # __all__ serializes all columns in Comment fields ='__all__'
        depth = 1If there is a foreign key, only the foreign key id is returned by default1All foreign key fields can be displayedCopy the code

Select * from * where depth = 1; select * from * where depth = 1; Return at this point:

Here the id associated with the primary table becomes the detailed primary table information.

2. Now that the sub-table can query the data of the primary table, we want to directly obtain the Comment records associated with all foreign keys in the primary table Good. Table ‘Comment’ +’_set’; table ‘Comment’ +’_set’; table ‘Comment’ +’_set’;

Eg. Ret = goo.objects.first ().comment_set.all();