Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

python - Django Filter latest files

I have a model like,

class Type(CommonBase):
    """
        Allowed document types
    """
    DOCUMENT_CLASS_CHOICES = (
        ('C', 'Credit Card'),
        ('D', 'Debit Card'),
        ('SD', 'Supporting Documents'),
    )
    MODEL_TYPE_CHOICE = (
        ('person', 'Person'),
        ('bank', 'Bank'),
        ('all', 'All')
    )
    document_title = models.CharField(max_length=100)
    document_class = models.CharField(choices=DOCUMENT_CLASS_CHOICES, max_length=3, default='C')
    model_type = models.CharField(choices=MODEL_TYPE_CHOICE, max_length=50, default='person')

class Document(CommonBase):
  
    doc_type = models.ForeignKey(Type, on_delete=models.PROTECT)
    uploaded_datetime = models.DateTimeField(null=True, blank=True)
    user = models.ForeignKey(Person, on_delete=models.CASCADE)
    comment = models.CharField(max_length=200, null=True, blank=True)

I can upload Multiple credit card or multiple debit card details against the same user.

So if a user has uploaded 2 credit card documents and 3 debit card documents. I need to get all the documents uploaded against that user but there should be only one credit card and debit card document which is the latest

docs = Documrnt.objects.filter(user=user)

this gives me all the documents(2 credit card docs and 3 debit card docs) uploaded against that particular user. But I need only the latest uploaded debit card and credit card details in result

How the query is supposed to be?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you want is the descending behavior of the order_by.

Oldest items first.

Document.objects.order_by('uploaded_datetime')

Newest items first. (what you want)

Document.objects.order_by('-uploaded_datetime')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...