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.
Related
I'm working on a website that has to do with user entering data to fields of a table. There is (input type=date) in top of the page. I want the user to enter values daily. but I want to save that data in the database according to that day and if the user change the date, I want to clear some fields for that day for a new fresh entry.
I also don't know if there should be a datefield in model or not?? If so, would I have to populate the database with lots of dates? and if it reach the last date, I have to populate it again and so on??
How I go about doing this?
I tried looking for a solution but couldn't find one that seems good. I found I could use crontab in django or scheduler but I don't think this is the optimum solution.
I'm looking to connect my website with Salesforce and have a view that shows a breakdown of a user's activities in Salesforce, then calculate an overall score based on assigned weights to each activity. I'm using Django-Salesforce to initiate the connection and extend the Activity model, but I'm not sure I've setup the Activity or OverallScore classes correctly.
Below is my code for what I already have. Based on other questions I've seen that are similar, it seems like a custom save method is the suggested result, but my concern is that my database would quickly become massive, as the connection will refresh every 5 minutes.
The biggest question I have is how to setup the "weighted_score" attribute of the Activity class, as I doubt what I have currently is correct.
class Activity(salesforce.models.Model):
owner = models.ManyToManyField(Profile)
name = models.CharField(verbose_name='Name', max_length=264,
unique=True)
weight = models.DecimalField(verbose_name='Weight', decimal_places=2,
default=0)
score = models.IntegerField(verbose_name='Score', default=0)
weighted_score = weight*score
def __str__(self):
return self.name
class OverallScore(models.Model):
factors = models.ManyToManyField(Activity)
score = Activity.objects.aggregate(Sum('weighted_score'))
def __str__(self):
return "OverallScore"
The ideal end result would be each user logged in gets a "live" look at their activity scores and one overall score which is refreshed every 5 minutes from the Salesforce connection, then at the end of the day I would run a cron job to save the end of day results to the database.
Excuse a late partial response only to parts of question that are clear.
The implementation of arithmetic on fields in weighted_score depends on your preferences if your prefer an expression on Django side or on Salesforce side.
The easiest, but very limited solution is by #property decorator on a method.
class Activity(salesforce.models.Model):
... # the same fields
#property
def weighted_score(self)
return self.weight * self.score
This can be used in Python code as self.weighted_score, but it can not be passed any way to SOQL and it gives you not more power than if you would write a longer (self.weight * self.score) on the same place.
Salesforce SOQL does not support arithmetic expressions in SELECT clause, but you can define a custom "Formula" field in Salesforce setup of the Activity object and use it as normal numeric read only field in Django. If the Activity would be a Master-Detail Relationship of any other Salesforce object you can apply very fast Sum, max or average formula on that object.
ManyToMany field require to create the binding object in Salesforce Setup manually and to assign it to the through attribute of the ManyToMany field. An example is on wiki Foreign Key Support. As a rule of thumb your object definition must first exist in Salesforce with useful relationships (it can be Lookup Relationship or Lookup Relationship) and manageable data structure. Then you can run python manage.py inspectdb --database=salesforce ... table names (optionally a list of API Names of used tables, separated by spaces) That is much code to prune many unnecessary fields and choices, but still easier and reliably functional than to ask someone. Salesforce has no special form of custom ManyToMany relationship, therefore everything is written by ForeignKey in models.py. Master-Detail is only a comment on the ForeignKey. You can finally create a ManyToMany field manually, but it is mainly only a syntactic sugar to have nice mnemonic name for a forward and reverse traversing by the two foreign keys on the "through=" binding object.
(The rest of question was too broad and unclear for me.)
Let's assume I am developing a service that provides a user with articles. Users can favourite articles and I am using Solr to store these articles for search purposes.
However, when the user adds an article to their favourites list, I would like to be able to figure out out which articles the user has added to favourites so that I can highlight the favourite button.
I am thinking of two approaches:
Fetch articles from Solr and then loop through each article to fetch the "favourite-status" of this article for this specific user from MySQL.
Whenever a user favourites an article, add this user's ID to a multi-valued column in Solr and check whether the ID of the current user is in this column or not.
I don't know the capacity of the multivalued column... and I also don't think the second approach would be a "good practice" (saving user-related data in index).
What other options do I have, if any? Is approach 2 a correct approach?
I'd go with a modified version of the first one - it'll keep user specific data that's not going to be used for search out of the index (although if you foresee a case where you want to search for favourite'd articles, it would probably be an interesting field to have in the index) for now. For just display purposes like in this case, I'd take all the id's returned from Solr, fetch them in one SQL statement from the database and then set the UI values depending on that. It's a fast and easy solution.
If you foresee that "search only in my fav'd articles" as a use case, I would try to get that information into the index as well (or other filter applications against whether a specific user has added the field as a favourite). I'd try to avoid indexing anything more than the user id that fav'd the article in that case.
Both solutions would however work, although the latter would require more code - and the required response from Solr could grow large if a large number of users fav's an article, so I'd try to avoid having to return a set of userid's if that's the case (many fav's for a single article).
I am trying to create a model for a Django app to handle invoicing, but I'm unsure of the right approach. The invoice must be a snapshot of the values at a given point in time. If you change the price of an item today, it can't affect a prior invoice. I also need to maintain a full revision history for each invoice.
An invoice can have up to forty different attributes, most of which will be left empty. The invoice has different addresses as well, such as the sender, receiver and postal addresses. An invoice also contains lines, which would each have their own values.
You need to set up a transaction table to record changes in invoices. This table can have links to address tables for different addresses. You would want to save this Invoice
Transaction table to the Client Table, so you have the deal points available at any time.
Django has built in fields for saving dates, so you can use those at different places to auto-record the dates in your transaction tables. Examples of these fields in Django are:
from django.db import models
class MyModel(models.Model):
created = models.DateField(auto_now_add=True)
modified = models.DateField(auto_now=True)
My recommendation would be to create a link in the Client table as a Many-to-Many to the transaction table. And each time an invoice occurs / changes. Join it onto this field. Then you can reference the transaction table by date, most recent, etc... to get the info that you need. You can set a BooleanField for the current Invoice, etc.
I want to generate the list of various milestones to accomplish something, and the deadline for each of them is calculated dynamically from a final date given by the user.
I'm not sure about the best way to handle this. The first idea that came to my mind is to write some template (not django template here) file on the server containing the necessary informations for generating all the steps, which will be fetched once for every new user, and used to create a list of milestone objects from a milestone class (some generic model in django). Maybe something written in json :
{"some_step":
{
"start_date" = "final_date-10",
"end_date" = "final_date-7",
}
}
and the corresponding model
class Milestone(models.Model):
name = models.Charfield()
start_date = models.DateField()
end_date = models.DateField()
def time_to_final(self,time):
return self.final_date-time
strings like the "finaldate-10" would be converted by some routine and passed at the registration time to the time_to_final method, when initializing the data for the new user in the database.
However I'm not sure it's the best approach. Though it won't be used by millions of people, I'm worried about possible negative impacts on the server performances ? Is there a better, maybe more pythonic way ?
EDIT for more clarification :
A user wants to do complete something at date D0.
My app generates the steps like this :
do step 1 from date D1i to date D1f
do step 2 from date D2i to date D2f
-...
until date D0 is reached and all tasks are completed
All the dates are calculated when D0 is provided.
All the steps are generated for every user.
What have templates got to do with this? Design your models first - maybe you need a Steps model with a foreign key to User and a foreign Key to Milestone (or maybe not - I'm not clear from your description).
Only when you've got the data clear in your mind start thinking about templates etc.
The great thing about django is that once you've made your models you can use the admin interface to enter some data. It will quickly become clear whether you've modeled your problem correctly.
Don't worry about performance, get your data structures clear, make it work and if you find it isn't running fast enough (unlikely) optimize it.