开发者

Querying by related object value

开发者 https://www.devze.com 2023-03-30 12:42 出处:网络
I am setting up a simple billing system, where I have a table that lists users and 开发者_开发技巧the day they are supposed to be billed. Each user only has one row of this table associated with them.

I am setting up a simple billing system, where I have a table that lists users and 开发者_开发技巧the day they are supposed to be billed. Each user only has one row of this table associated with them.

I need to query the database on a daily basis to get a list of users to be billed on that day.

The model is:

class BillingDay(models.Model):
    user = models.ForeignKey(User)
    day = models.IntegerField(max_length=2)

How would I query against the day field? User.objects.filter(billingday=1) looks at the ID, but I'm looking i need to get a list of users with 1 as the value for day in billingday


User.objects.filter(billingday__day=1)

Just as a note, though, you might want to rethink how you're setting this up before you get too far down the rabbit hole. Will users have multiple billing days? My guess would be no. If that's the case, there's no reason for a BillingDay model. It only adds complexity and fragments data. The billing day could just be a field on your user profile.

Now, creating a user profile for a User is in principle no different that having a BillingDay model as a way to add extra data to User, but it's far more extensible. Django has builtin methods for having a user profile associate with every User, and you can more data to the same user profile object over time. Whereas, BillingDay would be relegated to just one data point and you'd later have to add additional models (more complexity and fragmentation of data) for other data points down the line.

See Django's documentation on user profiles.

0

精彩评论

暂无评论...
验证码 换一张
取 消