# 24、related\_namerelated\_query\_name 的区别



## related\_name/related\_query\_name 的区别

> related\_name/related\_query\_name 一般出现在有 Foreignkey 或者 ManyToManyField 字段的时候

### 一般查询

```python
class Department(models.Model):
 　　title = models.CharField(verbose_name='部门',max_length=32)

class UserInfo(models.Model):
 　　depart = models.ForeignKey(verbose_name='部门',to='Department')
 　　user = models.CharField(verbose_name='用户',max_length=32)
 　　pwd = models.CharField(verbose_name='用户', max_length=32)
```

* 查询

```python
正向查询---用点
 user_object = UserInfo.objects.get(id=1)
 user_object.depart

反向查询---表名小写+set
 depart_object = Department.objects.get(id=9)
 depart_object.userinfo_set.all()
```

### related\_query\_name

```python
class Department(models.Model):
 title = models.CharField(verbose_name='部门',max_length=32)

class UserInfo(models.Model):
 depart=models.ForeignKey(verbose_name='部门',to='Department',related_query_name="u")
 user = models.CharField(verbose_name='用户',max_length=32)
 pwd = models.CharField(verbose_name='用户', max_length=32)
```

* 查询

```python
正向查询---用点
 user_object = UserInfo.objects.get(id=1)
 user_object.depart

反向查询---表名小写+set
 depart_object = Department.objects.get(id=9)
 depart_object.u_set.all()
```

### related\_name

```python
class Department(models.Model):
 title = models.CharField(verbose_name='部门',max_length=32)

class UserInfo(models.Model):
 depart=models.ForeignKey(verbose_name='部门',to='Department',related_name="u")
 user = models.CharField(verbose_name='用户',max_length=32)
 pwd = models.CharField(verbose_name='用户', max_length=32)
```

* 查询

```python
正向查询---用点
 user_object = UserInfo.objects.get(id=1)
 user_object.depart
 
反向查询---表名小写+set
 depart_object = Department.objects.get(id=9)
 depart_object.u.all()
```
