Django - 外键,一组id

时间:2017-05-20 19:14:43

标签: python django django-models django-views django-queryset

让我们说模型的构造如下:

class Worker(models.Model):
    name_char = models.CharField(max_length=4,null=True, blank=True)
    body_parts_mtm = models.ManyToManyField('BodyPart')

class Job(models.Model):
    job_name = models.CharField(max_length=6,unique=True)  
    job_reference_mtm = models.ManyToManyField('JobReferenceCode') 

class JobReferenceCode(models.Model):
    job_ref_char = models.CharField(max_length=13)
    worker_mtm = models.ManyToManyField('Worker')

class BodyPart(models.Model):
    body_part_name_text = models.TextField()

class MembersSimilarity(models.Model):
    similarity_score_float = models.FloatField(max_length=10)
    worker_fk = models.ForeignKey(Worker,on_delete=models.CASCADE)
    job_fk = models.ForeignKey(Job,on_delete= models.CASCADE)

    #not sure if I need this field to do what I want but here it is:
    bodypart_fk = models.ForeignKey(BodyPart,on_delete=models.CASCADE)

在我的网站上,用户可以查找JobReference,我想提供一个特定的输出:一个表格,其中行数由(作业,[BodyParts])的组合控制。

为了做到这一点,在我的视图上,我认为找到解决这个问题的方法是创建一个具有这种结构的函数(简化):

job_ref_code = 1
job_query = Job.objects.filter(job_reference_mtm=job_ref_code)

for job in unique_job_query:
    sims = MembersSimilarity.objects.filter(job_fk=job)
    workers_from_sim= Worker.objects.filter(id__in=sims.values('worker_fk'))
    unique_ids_list = []
    for worker in workers_from_sim:
        combination = set(worker.cath_mtm.all())
        if combination not in unique_ids_list:
            unique_ids_list.append(combination)
        #All of this "for worker" loop to construct this list; do I need to acces like it ? Let say this list has this structure = [[1,2,3],[1],[1,2]]
    for body_part_combination in unique_body_ids_list:
         sim_queryset=MembersSimilarity.objects.filter(job_fk=job_query,bodypart_fk=body_part_combination)

#Note sim_query_set : if I can access to these similarities here (specific similarities of a job and a combination of body parts, my problem will be solved.

有可能过滤这样的东西吗?我需要区分具有特定身体部位的工人和每个工作。我找了怎么做但没找到任何东西,我也问这个问题也有关于如何优化我的视图函数的意见(例如:循环来构造不同的bodypart id组合......)

我知道这个问题相当庞大,但我现在很难挣扎,尝试了很多不同的模型结构......任何帮助都不仅仅是欣赏,谢谢!

1 个答案:

答案 0 :(得分:0)

我不知道我是否必须这样做但是在@Mani的帮助下,我已经找到了寻找的位置,并找到了这个主题:Davor Lucic's answer并最终解决了我的问题。

在我的情况下,我尝试了他所有的答案,最后选择了.filter循环。 根据我的问题,我解决了这个问题:

pre_queryset = #a query set of MembersSimilarity
post_queryset = pre_queryset.filter(job_fk=1,bodypart‌​_fk=1 AND 2)

假设我有一个body_part_fk列表,并希望过滤pre_queryset:

list_ids=[1,2]
i=0
while i < len(list_ids)-1:
    if i==0: #use the prequeryset
        post_queryset = pre_queryset.filter(job_fk=job,bodypart_fk=list_ids[i])
    else:
        post_queryset = post_queryset.filter(job_fk=job,bodypart_fk=list_ids[i])
    i+=1