forienkey 通过属性限制
staff_member = models.ForeignKey(
User,
on_delete=models.CASCADE,
limit_choices_to={'is_staff': True},
)
forienkey 通过函数限制
def limit_pub_date_choices():
return {'pub_date__lte': datetime.date.utcnow()}
limit_choices_to = limit_pub_date_choices
forienkey 反查
# Declare the ForeignKey with related_query_name
class Tag(models.Model):
article = models.ForeignKey(
Article,
on_delete=models.CASCADE,
related_name="tags",
related_query_name="tag",
)
name = models.CharField(max_length=255)
# That's now the name of the reverse filter
Article.objects.filter(tag__name="important")
反查代码
from django.db import models
# Create your models here.
class Article(models.Model):
ar_name=models.CharField(max_length=255)
def __str__(self):
return self.ar_name
class Tag(models.Model):
article = models.ForeignKey(
Article,
on_delete=models.CASCADE,
related_name="tags",
related_query_name="tag",
)
name = models.CharField(max_length=255)
def __str__(self):
return self.ar_name+' '+self.article.ar_name
'''
# 初始化数据
from CForientApp.models import *
Article(ar_name='a1111').save()
Article(ar_name='a2222').save()
Article(ar_name='a3333').save()
Article(ar_name='a4444').save()
a5=Article(ar_name='a4444')
a6=Article(ar_name='a4444')
a5.save()
a6.save()
Tag(article=a5,name='tag01').save()
from CForientApp.models import *
Article.objects.filter(tag__name='tag01')
Article.objects.exclude(tag__name='tag01')
'''