【问题标题】:Django: How to get most recent object from different model?Django:如何从不同的模型中获取最新的对象?
【发布时间】:2021-05-23 11:03:40
【问题描述】:

我正在尝试显示以下输出,其中 Cylinder、Issue 和 Return 是不同的模型,我期望的视图是圆柱表,其中仅显示最近创建的 issue 和 return 条目, 例如:

cylinderId=100 在 issue 表和 return 表中有两个条目,但在柱面表中只有最近创建的出现:-

cyId |   createdAt |  issuedDate  | username  | ReturnDate

100  |   5may,13:00|  6may,14:00  | anyone    | 7may,15:00

这里是模型:-

class Cylinder(models.Model):
    stachoice=[
    ('Fill','fill'),
    ('Empty','empty') 
    ]
    substachoice=[
    ('Available','available'), 
    ('Unavailable','unavailable'),
    ('Issued','issued') 
    
    ]
    cylinderId=models.CharField(max_length=50,primary_key=True,null=False)
    gasName=models.CharField(max_length=200)
    cylinderSize=models.CharField(max_length=30)
    Status=models.CharField(max_length=40,choices=stachoice,default='fill')
    Availability=models.CharField(max_length=40,choices=substachoice,default="Available")
    EntryDate=models.DateTimeField(default=timezone.now)
    
    

    def get_absolute_url(self):
        return reverse('cylinderDetail',args=[(self.cylinderId)])

    def __str__(self):
        return str(self.cylinderId)

class Issue(models.Model):
    cylinder=models.ForeignKey('Cylinder',on_delete=models.CASCADE)
    userName=models.CharField(max_length=60,null=False)
    issueDate=models.DateTimeField(default=timezone.now)
    
    def save(self,*args,**kwargs):
        if not self.pk: 
            if self.cylinder.Availability=='Available':
                Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued'))

        super().save(*args,**kwargs)
        
    def __str__(self):
        
        return str(self.userName) 


class Return(models.Model):
    fill=[
    ('Fill','fill'),
    ('Empty','empty'),
    ('refill','Refill')
    ]

    ava=[
    ('yes','YES'),
    ('no','NO')
    ]
    cylinder=models.ForeignKey('Cylinder',on_delete=models.CASCADE)
    availability=models.CharField(max_length=20,choices=ava)
    status=models.CharField(max_length=10,choices=fill)
    returnDate=models.DateTimeField(default=timezone.now)
    def save(self,*args,**kwargs):
        if not self.pk:

            if self.cylinder.Availability=='Issued':
                
                if self.availability=='YES' or self.availability=='yes':
                    Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Available')
                    if self.status=='empty' or self.status=='Empty':
                        Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Empty')
                else:
                    Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Unavailable')
                    if self.status=='refill' or self.status=='Refill':
                        Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Refill')
                    if self.status=='empty' or self.status=='Empty':
                        Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Empty')


        super().save(*args,**kwargs)

    def __str__(self):
        return str(self.cylinder)

查看:-

def cylinderListView(request):
    
    cylinder=Cylinder.objects.pefetch_related().order_by('-EntryDate')
    
    return render(request,'entry/cylinderList.html',locals())

模板圆柱列表.html:-

{%for cy in cylinder %}
                    <tr bgcolor="#e6f0ff" align="center">
                        
                    <td align="center" height="10" 
                width="50"><a style="border-width: 0px" href="{{cy.get_absolute_url}}">{{cy.cylinderId}}<a></td>
               
                    <td align="center" height="10" 
                width="50">{{cy.EntryDate}}</td>
                    <td align="center" height="10" 
                width="50">{{cy.gasName}}</td>
                <td align="center" height="10" 
                width="50">
                    {{cy.cylinderSize}}</td>
                    <td align="center" height="10" 
                width="50">
                    {{cy.Status}}</td>
                    <td align="center" height="10" 
                width="50">{{cy.Availability}}</td>

               
                {% if cy.issue_set.all%}
                
                {% for issue in cy.issue_set.all %}

               
                <td align="center" height="10" 
                width="50">{{issue.issueDate}}</td>
                <td align="center" height="10" 
                width="50">{{issue.userName}}</td>
                
               {% endfor %}
                
                {% else %}
                <td align="center" height="10" 
                width="50">-</td>
                <td align="center" height="10" 
                width="50">-</td>

                {% endif%}


                 {% if cy.return_set.all%}
                
                {% for return in cy.return_set.all %}
                
                <td align="center" height="10" 
                width="50">{{return.returnDate}}</td>
              
               {% endfor %}
                
                {% else %}
                
                <td align="center" height="10" 
                width="50">-</td>

                {% endif%}


                                    
                
                    </tr>

                    {% endfor %}
                </tbody>

            {% else %}

这是我期待的视图:-

对于这个结果我该怎么办?请帮忙:)

【问题讨论】:

  • 请将您的模型添加到问题中。
  • @AbdulAzizBarkat 完成
  • @ShagunRaghav 澄清一下,您想获取最新一期并返回每个气缸的行吗?
  • @yovelcohen 是的
  • 您应该使用 prefetch_related 来完成此操作。请阅读文档。 docs.djangoproject.com/en/3.2/ref/models/querysets/…

标签: python django


【解决方案1】:

你可以使用latest()方法

Cylinder.objects.latest('EntryDate')

这将根据 CreatedAt 字段返回表中最新的 Cylinder 对象。

如果您想列出最新的气缸,请使用

Cylinder.objects.all().order_by('-EntryDate')    

【讨论】:

  • 感谢您的关注:),但它只会返回单个气缸条目,我想在问题表和返回表中显示所有气缸 ID 及其各自的最新条目。
  • 未产生预期的输出。
  • 因此,如果我尝试获取问题条目(圆柱体_obj.issue_set.all()),它将返回为该圆柱体 id 创建的所有已发布条目,如图所示(我已附加我的问题)问题表可以有多个条目用于单个气缸 ID(例如:气缸 ID = 100),但我只想要最近为气缸 ID 创建的条目,但执行此查询将返回所有条目。跨度>
【解决方案2】:

只需将它们查询为Cylinder.objects.order_by('-pk')

【讨论】:

  • 通过执行这个查询,我能获取问题条目并返回条目吗?如果是,那么如何?
  • 您可以将单个CylinderIssue 条目查询为cylinder_obj.issue_set.all()。如果您想要获得的 cylinder 列表的所有 issue 条目,那么可以通过 for 循环。 Return 也一样。
  • 通过查询这个问题并返回,它将返回为该圆柱体 ID(圆柱体 ID=pk)创建的所有条目,但我只需要最近为该特定圆柱体 ID 创建的一个条目。请注意我添加的表格图片。
  • 只需将cylinder_obj.issue_set.order_by('-pk') 用于您可以做的最后三个对象list(cylinder_obj.issue_set.order_by('-pk'))[:-3]
猜你喜欢
  • 2011-01-05
  • 2021-02-14
  • 2020-04-22
  • 2020-04-06
  • 2013-11-21
  • 1970-01-01
  • 1970-01-01
  • 2011-10-07
  • 2014-03-26
相关资源
最近更新 更多