zoukankan      html  css  js  c++  java
  • django : related_name and related_query_name

    This post is about two Django ForeignKey parameters

    related_name
    related_query_name
    

    See an example below

    class Cluster(models.Model):
    	_id = models.UUIDField(unique=True, null=False, default=uuid.uuid1)
    	name = models.CharField(max_length=200, unique=True, null=False)
    
    
    class Node(models.Model):
    	_id = models.UUIDField(unique=True, null=False, default=uuid.uuid1)
    	name = models.CharField(max_length=200, unique=True, null=False)
    	cluster = models.ForeignKey(
    		Cluster,
    		on_delete=models.PROTECT,
    		to_field='_id',
    		db_constraint=False
    	)
    

    We did not set relatd_name and related_query_name here, so django will use the default. Related_name will be node_set (mode name with a _set) and related_query_name will be node(model name).

    The value of the two parameter is not important. What we care about is the usage of this two parameters.

    To discuss that, we need to find a way to call this two types of models. Here we call the model with foreign key 'slave_model' and the other model 'master_model'.

    The related_name is used for the master_model object to refer back to slave_models. For example:

    >>> for node_obj in  c1.node_set.all():
    ...     print(node_obj.cluster_id)
    ... 
    26f0655e-bf2b-11e8-8a30-f000ac192ced
    26f0655e-bf2b-11e8-8a30-f000ac192ced
    >>> c1._id
    UUID('26f0655e-bf2b-11e8-8a30-f000ac192ced')
    

    The c1 is a master_model object. The related_name is now one attribute of it. With this attr, master_model object can refer back to slave_models.

    The related_query_name usually used in two scenario.

    First, related_query_name used in filter. Lets see an example

    Cluster.objects.filter(key=value)
    

    Usually, the key should be column of cluster. With related_query_name , the key could be column of node. For example:

    >>> Cluster.objects.filter(node__name=n1.name)
    <QuerySet [<Cluster: Cluster object (4)>]>
    

    Please note that the node is the related_query_name and we always add two "_" between related_query_name and column name

    Second usage is

    Cluster.objects.filter(node__name=n1.name).values('column', 'column')
    

    Normally, you can specify the column of cluster to get the target column you want. With related_query_name , you can specify the column of node (slave_model).

    >>> Cluster.objects.filter(node__name=n1.name).values('name', 'node__name', 'node__pk')
    <QuerySet [{'name': 'c1', 'node__name': 'n1', 'node__pk': 5}]>
  • 相关阅读:
    使用 HTML5 可以做的五件很棒的事情
    分享最新20款非常棒的 CSS 工具
    最新17个紫色风格网页设计作品欣赏
    最新70佳很酷的名片设计作品欣赏
    50个优秀的名片设计作品欣赏
    推荐12个漂亮的CSS3按钮实现方案
    推荐10个很棒的 CSS3 开发工具
    30个复古风格的网页设计作品欣赏
    非常流行的十款 jQuery 插件推荐
    20个漂亮的WordPress作品集主题分享
  • 原文地址:https://www.cnblogs.com/kramer/p/9693918.html
Copyright © 2011-2022 走看看