将列表转换为Django查询集

huangapple go评论54阅读模式
英文:

Converting List to QuerySet Django

问题

以下是您的代码的翻译部分:

models.py

class Part(models.Model):
    series = models.CharField(max_length=100)
    number = models.CharField(max_length=100)
    brand = models.CharField(max_length=100)

class Request(models.Model):
    part_number = models.ForeignKey(Part, on_delete=models.CASCADE)
    brand = models.CharField(max_length=100)
    quantity = models.PositiveIntegerField()
    date = models.DateField()

class Quota(models.Model):
    part_number = models.ForeignKey(Part, on_delete=models.CASCADE)
    brand = models.CharField(max_length=100)
    quantity = models.PositiveIntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    supplier = models.CharField(max_length=100)
    date = models.DateField()

views.py

def requests_and_quotas(request):
    requests = Request.objects.all()
    quotas = Quota.objects.all()
    result = []
    for req in requests:
        match = False
        for quo in quotas:
            if (req.part_number.series == quo.part_number.series) and (abs((req.date - quo.date).days) <= 2):
                result.append({'request': req, 'quota': quo})
        if not match:
            result.append({'request': req, 'quota': None})
    return render(request, 'requests_and_quotas.html', {'result': result,})

至于您提到的问题,您想要将result列表转换为一个QuerySet对象,但是在Django中,QuerySet通常是从数据库查询中获取的,而不是手动创建的。如果您想要应用django_filters,您可以尝试将您的数据查询转换为一个QuerySet对象。例如,您可以使用filter()annotate()方法来构建您的查询,然后将其传递给django_filters。以下是一个示例:

from django.db.models import F

result_qs = Request.objects.annotate(
    match_quota=Quota.objects.filter(
        part_number__series=F('part_number__series'),
        date__range=(F('date') - timedelta(days=2), F('date') + timedelta(days=2))
    )
)

# 现在,result_qs 包含了您想要的查询结果,您可以使用 django_filters 进行进一步的筛选。

这只是一个示例,具体的逻辑可能需要根据您的需求进行修改。希望这可以帮助您解决问题。

英文:

models.py

class Part(models.Model):
    series = models.CharField(max_length=100)
    number = models.CharField(max_length=100)
    brand = models.CharField(max_length=100)

class Request(models.Model):
    part_number = models.ForeignKey(Part, on_delete=models.CASCADE)
    brand = models.CharField(max_length=100)
    quantity = models.PositiveIntegerField()
    date = models.DateField()

class Quota(models.Model):
    part_number = models.ForeignKey(Part, on_delete=models.CASCADE)
    brand = models.CharField(max_length=100)
    quantity = models.PositiveIntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    supplier = models.CharField(max_length=100)
    date = models.DateField()

views.py

def requests_and_quotas(request):
    requests = Request.objects.all()
    quotas = Quota.objects.all()
    result = []
    for req in requests:
        match = False
        for quo in quotas:
            if (req.part_number.series == quo.part_number.series) and (abs((req.date - quo.date).days) &lt;= 2):
                result.append({&#39;request&#39;: req, &#39;quota&#39;: quo})
        if not match:
            result.append({&#39;request&#39;: req, &#39;quota&#39;: None})
    return render(request, &#39;requests_and_quotas.html&#39;, {&#39;result&#39;: result,})

I wanted to connect django_filters, but ran into a problem AttributeError: 'list' object has no attribute '_meta'. How can I change the logic of my code to retrieve a QuerySet object?

result_qs = QuerySet(result) it didn't help

答案1

得分: 1

你可以创建一个包含你的对象在列表中的ID的列表。然后简单地按照这些ID进行筛选。

instances = [<MyModel: 1>, <MyModel: 2>]
list_of_ids = [inst.id for inst in instances]
queryset = MyModel.objects.filter(id__in=list_of_ids)
英文:

You can create a list of ids of your objects in the list. Then simply filter by them.

instances = [&lt;MyModel: 1&gt;, &lt;MyModel: 2&gt;]
list_of_ids = [inst.id for inst in instances]
queryset = MyModel.objects.filter(id__in=list_of_ids)

答案2

得分: 0

以下是翻译好的部分:

# 通过将它们附加到一个数组中,然后根据`date`使用Python的`chain`迭代工具对它们进行排序,您可以合并2个模型。

from itertools import chain

这是`requests_and_quotas`函数

def requests_and_quotas(request):
    requests = Request.objects.all()
    quotas = Quota.objects.all()
    queryset = []
    
    queryset.append(requests)
    queryset.append(quotas)
    if len(queryset):
        queryset = sorted(chain(*queryset), reverse=True, key=lambda queryset: queryset.date)
    
    return render(request, 'requests_and_quotas.html', {'queryset': queryset,})

然后根据模型的唯一字段决定模板中的显示内容的方法如下

{% for item in queryset %}
    {% if item.supplier %}
        <!-- 这里呈现Quota模型 -->
    {% else %}
        <!-- 这里呈现Request模型 -->
    {% endif %}
{% endfor %}
英文:

You can merge 2 models by appending them in one array and then sort them based on date by using Python chain itertools

from itertools import chain

here is the requests_and_quotas function

def requests_and_quotas(request):
    requests = Request.objects.all()
    quotas = Quota.objects.all()
    queryset = []
    
    queryset.append(requests)
    queryset.append(quotas)
    if len(queryset):
            queryset = sorted(chain(*queryset), reverse=True, key=lambda queryset: queryset.date)
        
    return render(request, &#39;requests_and_quotas.html&#39;, {&#39;queryset&#39;: queryset,})

then here is how you can decide what will appear in the template based on unique field of the models

{% for item in queryset %}
    {% if item.supplier %}
        &lt;!-- here Quota model render --&gt;
    {% else %}
        &lt;!-- here Request model render --&gt;
    {% endif %}
{% endfor %}

huangapple
  • 本文由 发表于 2023年2月10日 16:17:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408475.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定