django accessing class variables in a view
i want to make a notification function, and i need fields from 2 different models. how can i access those fields? in my notification view i wrote this
data = Notices.objects.filter(last_login<date_follow)
where last_login belongs to the model class User , and date_follow to Follow but it is not a proper and correct way of acce开发者_如何学编程ssing those variables. How can i access them? I need to compare the two dates for realising the notifications that one did not see since his last login.
Thanks!
In general you want to join two tables. In Django this is best possible if you have a foreign key from one table to the other. You maybe want / have your models like this:
class User(models.Model):
last_login = ...
class Notice(models.Model):
...
class Follow(models.Model):
user = models.ForeignKey(User)
notice = models.ForeignKey(Notice)
date_follow = ...
and your query
Notice.objects.filter(follow_set__date_follow__gt = follow_set__user__last_login)
I don't have tested this query, but here 'follow_set' is automatically created by Django and is a Manager which returns the reverse set for the foreign key. If you want, you can use 'related_name' with your foreign key to choose another name here.
精彩评论