如何按时间过滤两个模型对象?

发布于 2024-11-09 03:37:18 字数 630 浏览 0 评论 0 原文

models.py:

class Post(models.Model):
  msg=models.TextField("Shout it out!:")
  college=models.ForeignKey('College')
  time=models.DateTimeField(auto_now_add=True)

class Feed(models.Model):
  gender = models.CharField(max_length=5, choices=GENDER_CHOICES, default='girl')
  location=models.CharField(max_length=25, choices=LOCATION_CHOICES)
  msg = models.TextField("Message")
  email = models.EmailField("Email:",blank=True, null = True)
  college=models.ForeignKey('College')
  time=models.DateTimeField(auto_now_add=True)

在模板中,我希望在根据时间过滤的流中一起显示提要和帖子。我该怎么做?我们如何按时间过滤两个模型对象?是否可以?需要帮助。谢谢。

models.py:

class Post(models.Model):
  msg=models.TextField("Shout it out!:")
  college=models.ForeignKey('College')
  time=models.DateTimeField(auto_now_add=True)

class Feed(models.Model):
  gender = models.CharField(max_length=5, choices=GENDER_CHOICES, default='girl')
  location=models.CharField(max_length=25, choices=LOCATION_CHOICES)
  msg = models.TextField("Message")
  email = models.EmailField("Email:",blank=True, null = True)
  college=models.ForeignKey('College')
  time=models.DateTimeField(auto_now_add=True)

In templates I wish to show both feeds and posts together in a stream filtered according to time. How do I do it? How can we filter both model objects by time? Is it possible? need Help. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

本王不退位尔等都是臣 2024-11-16 03:37:18

您可以考虑创建一个包含公共字段的基类。然后,您可以执行类似于 BaseFeed.objects.all().order_by('time') 的查询,并在模板中迭代它,但您可以将每个结果项视为其实际类型。

class BaseFeed(models.Model):
    ....
    msg = models.TextField("Message")
    college=models.ForeignKey('College')
    time=models.DateTimeField(auto_now_add=True)
    ....

以下是我在做类似事情时经常参考的一些片段。

http://www.djangosnippets.org/snippets/1034/

http://www.djangosnippets.org/snippets/1031/

http://adam.gomaa.us/blog/2009/feb/16/subclassing-django-querysets/

You might consider creating a base class containing the common fields. Then, you could do a query similar to BaseFeed.objects.all().order_by('time') and iterate through it in your template, but you could treat each result item as the type that it really is.

class BaseFeed(models.Model):
    ....
    msg = models.TextField("Message")
    college=models.ForeignKey('College')
    time=models.DateTimeField(auto_now_add=True)
    ....

Here are some snippets that I always refer to when doing something similar.

http://www.djangosnippets.org/snippets/1034/

http://www.djangosnippets.org/snippets/1031/

http://adam.gomaa.us/blog/2009/feb/16/subclassing-django-querysets/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文