1. 程式人生 > >Django CRM查詢(一對多,多對多以及相關的反查)

Django CRM查詢(一對多,多對多以及相關的反查)

mce field 需要 fff etime fcc nbsp pre 使用

Customer模型:

class Customer(models.Model):

    name = models.CharField(max_length=32)
qq = models.CharField(max_length=64,unique=True)
weixin = models.CharField(max_length=64,blank=True,null=True)
age = models.PositiveSmallIntegerField(blank=True,null=True)
referral_from = models.ForeignKey("Customer",related_name="my_referrals",
blank=True,null=True,verbose_name="轉介紹",on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True) #auto_now_add自動增加

def __str__(self):
return self.name

class Meta:
verbose_name_plural = "客戶信息表"
verbose_name = "客戶信息表"

----------------------------------------------------------
Enrollment模型:
class Enrollment(models.Model):
"""學員報名信息"""
customer = models.ForeignKey("Customer",on_delete=models.CASCADE,related_name=‘entries‘)
class_grade = models.ForeignKey("ClassList",on_delete=models.CASCADE)
enrollment_date = models.DateField()
def __str__(self):
#return self.customer

class Meta:
unique_together = ("customer","class_grade")
---------------------------------------------------------------------------
FollowUpRecord模型
class FollowUpRecord(models.Model):
customer = models.ForeignKey("Customer",on_delete=models.CASCADE)
content = models.TextField(max_length=1024)
def __str__(self):
return "%s" % self.customer
----------------------------------------------------------------------------
ClassList模型:
class ClassList(models.Model):
semester = models.PositiveSmallIntegerField(verbose_name="學期")
class_type_choices = ((0,‘脫產‘),(1,‘周末‘),(2,‘網絡‘))
start_date = models.DateField()
end_date = models.DateField()

-----------------------------------------------------------------------------------------------------------

使用ForeignKey查詢

正向查詢

關系模型Enrollment包含模型Customer關聯的ForeignKey, 模型Enrollment的實例可以通過關聯字段訪問Customer實例:

>>> e = Enrollment.objects.get(id=2)  #註意:此處不能用e =Enrollment.objects.filter(id=2)
>>> e.customer                        # 通過關聯字段訪問Customer實例

修改e.blog並調用save方法存入數據庫

>>>e.customer= some_customer
>>> e.save()

如果ForeignKey 字段有null=True 設置(即它允許NULL值),可以分配None來刪除對應的關聯性

>>> e.customer= None
>>> e.save()

反向查詢

已經得到模型Customer的實例,需要查詢該以該實例為外鍵的相關模型(如FollowUpRecord和Enrollment),可以使用查詢集API取出相應的實例。

外鍵沒有指定related_name的相關模型:FollowUpRecord
    customer = models.ForeignKey("Customer",on_delete=models.CASCADE)
反查找使用 模型類名小寫_set.all() ,方法如下:
>>>c = Customer.objects.get(id=1)
>>>c.followuprecord_set.all()
 
外鍵指定related_name的相關模型:Enrollment
customer = models.ForeignKey("Customer",on_delete=models.CASCADE,related_name=‘entries‘)
反查找不能使用 模型類名小寫_set.all(),需要使用related_name的值,方法如下:
>>>c = Customer.objects.get(id=1)
>>>c.entries.all()





Django CRM查詢(一對多,多對多以及相關的反查)