Database 如何扫描数据库并根据特定属性匹配模型?(django)
我有一个模型Database 如何扫描数据库并根据特定属性匹配模型?(django),database,django,object,filter,matching,Database,Django,Object,Filter,Matching,我有一个模型 class dog(models.Model): name = models.CharField(max_length=30, blank=True) type = models.CharField(max_length=30, blank=True) sex = models.CharField(max_length=30, blank=True) 还有一个观点 def dog_matching(request): # Create the ne
class dog(models.Model):
name = models.CharField(max_length=30, blank=True)
type = models.CharField(max_length=30, blank=True)
sex = models.CharField(max_length=30, blank=True)
还有一个观点
def dog_matching(request):
# Create the new dog, starting with data from the previous HTML page
name = request.session['name']
# Fill in the rest of the information on the current HTML page
if request.method == 'GET':
type = request.GET['type']
sex = request.GET['sex']
# Create an instance of the dog
dog_inst = dog(name=name, type=type, sex=sex)
# Save the instance to database
dog_inst.save()
# Perform matching and send email
当一只新狗被创建和保存时,我想在数据库中找到之前的每一只狗,其中“类型”匹配,“性别”不同。然后,对于每一场比赛,我希望通过电子邮件通知我,网站上的提交导致了一场比赛(例如,一封写着“Scruffles and JayJay match!”的电子邮件)
如何执行匹配操作,使我收到的每封电子邮件都对应于每个匹配
我正在尝试这样的东西
if dog_inst.sex = 'male':
for dog.objects.get(sex__iexact="female"):
test = dog.objects.get(sex__iexact="female")
if test.type = dog_inst.type:
#Send email (I can find documentation for this)
if dog_inst.sex = 'female':
for dog.objects.get(sex__iexact="male"):
test = dog.objects.get(sex__iexact="male")
if test.type = dog_inst.type:
#Send email (I can find documentation for this)
有什么想法吗?在Django,你通常会叫你的模特
狗
。然后可以使用dog
引用dog实例。我在回答中已经这样做了
主要问题是,当您应该使用filter()
时,您正在使用get()
。我想你会发现读一读这本书真的很有用
简而言之,当您想要获取特定对象时,可以使用get()
dog = Dog.objects.get(pk=5) # gets the dog with primary key 5
将新的雌性狗保存到数据库后,您希望查找与new\u dog
相同类型的所有雄性狗。这里我们使用filter()
我们可以根据性别和类型进行过滤,而不是检查循环中每只狗的类型
if new_dog.sex == 'female': # new_dog is the dog you have just created
dogs = Dog.objects.filter(sex__iexact="male", type=new_dog.type)
for dog in dogs:
# send email
为什么这会被否决?