how can I get objects that are associated with a user
I am creating this app for managing/tracking customers
I have form which is used to save customer personal info and another field which is how much they are willing to spend + We can assign the customer to a user to be dealt with.
e.g. user1 assigned to customer1, customer2, customer3
I want to get one amount they willing to spend from all customers assigned to user1
So for example something like this
[<user1: <customer1:$10> <customer2:$100> <customer3:$1000>]
And then sum the prices together so something like this [<user1: total:$1110>]
this is what I done but doesn't seem to work
annual_spend = Lead.objects.filter(assign_to=User).exclude(lead_status='converted').aggregate(Sum('annual_spend'))
How could I do this any ideas?
For specific user:
this_user = User.objects.get(id=ENTER USER ID HERE)
annual_spend['annual_spend__sum'] = Lead.objects.filter(assign_to=this_user).exclude(lead_status='converted').aggregate(Sum('annual_spend'))
or if you want it for the user that is authenticated:
annual_spend['annual_spend__sum'] = Lead.objects.filter(assign_to=request.user).exclude(lead_status='converted').aggregate(Sum('annual_spend'))
grand total for all Lead instances:
annual_spend['annual_spend__sum'] = Lead.objects.all().exclude(lead_status='converted').aggregate(Sum('annual_spend'))
For a table with value for each user:
all_users = User.objects.all()
values = {}
for this_user in all_users:
values[this_user.id] = Lead.objects.filter(assign_to=this_user).exclude(lead_status='converted').aggregate(Sum('annual_spend'))['annual_spend__sum']
Related
I have a tag system in Django with the following model;
class Data(models.Model):
new = models.ChardField()
is_tagged = models.BooleanField(default=False)
class Tag(models.Model):
data = models.ForeignKey(Data,on_delete=models.CASCADE,related_name="data")
status = models.CharField(verbose_name="New Status",max_length=10,null=True)
The tag status holds "positive", "negative", and "pass".
There is a page called "new tags" and around 100 users will enter the page at the same time.
There are 10000 data and users will enter the page and just click "positive", "negative", and "pass".
I want to show different data for each user.
EDIT
New1: id = 1,is_tagged=False
New2: id = 2,is_tagged=False
User 1: Display New1
User 2: Display New1
User 1: Tag: "Positive" and id = 1, is_tagged will be "True"
Because both user open the windows at the same time, after 1 second,
User 2: Tag: "Pass" and id = 1 , is_tagged will be "False"
I want to prevent this situation. It supposed to be;
User 1: Display New1
User 2: Display New2
So each user must display different News Data to tag.
Let's say a user tagged the new as "positive". If I will send the new with random() it can be the same at another user unluckily. And the user can tag as "pass". This status will make "Data" "is_tagged" False. But other users tagged "positive" before.
How can I prevent users see the same data at the same time?
If you need to get a random object, you could do something like:
import random
all_object_ids = Data.objects.all().values_list('id', flat=True) # gets list of all object ids
random_id = random.choice(all_object_ids) # picks a random id from list
random_tag = Data.objects.get(id=random_id)
I have a list of IDs which corresponds to a set of records (opportunities) in a database. I then pass this list as a parameter in a RESTful API request where I am filtering the results (tickets) by ID. For each match, the query returns JSON data pertaining to the individual record. However, I want to handle when the query does not find a match. I would like to assign some value for this case such as the string "None", because not every opportunity has a ticket. How can I make sure there exists some value in presales_tickets for every ID in opportunity_list? Could I provide a default value in the request for this case?
views.py
opportunities = cwObj.get_opportunities()
temp = []
opportunity_list = []
cw_presales_engineers = []
for opportunity in opportunities:
temp.append(str(opportunity['id']))
opportunity_list = ','.join(temp)
presales_tickets = cwObj.get_tickets_by_opportunity(opportunity_list)
for opportunity in opportunities:
try:
if opportunity['id'] == presales_tickets[0]['opportunity']['id']:
try:
for presales_ticket in presales_tickets:
cw_engineer = presales_ticket['owner']['name']
cw_presales_engineers.append(cw_engineer)
except:
pass
else:
cw_engineer = 'None'
cw_presales_engineers.append(cw_engineer)
except AttributeError:
cw_engineer = ''
cw_presales_engineers.append(cw_engineer)
So, lets say you have a Ticket model and Opportunity model. Connected via a foreign key.
class Opportunity(models.Model):
... some fields here ...
class Ticket(models.Model):
opportunity = models.ForeignKey(Opportunity)
and in your view, you get a list of opportunity ids
def some_view(request):
ids = request.GET['ids']
It sounds, like what you want is to fetch all the tickets for the supplied opportunities and add some default processing for the opportunities that do not have tickets. If that is the case, why not do something like
def some_view(request):
ids = request.GET['ids']
tickets = Ticket.objects.filter(opportunity__id__in=ids)
results = []
for ticket in tickets:
result = ... do your thing here ...
results.append(result)
# now handle missing opportunities
good_ids = tickets.values_list('opportunity__id', flat=True).distinct()
for id in ids:
if id not in good_ids:
result = ... do your default processing ...
results.append(result)
Is that what you are trying to do?
I'm trying to get into djangos annotate, but can't quite figure out how it works exactly.
I've got a function where I'd like to annotate a queryset of customers, filter them and return the number of customers
def my_func(self):
received_signatures = self.customer_set.annotate(Count('registrations').filter().count()
Now for the filter part, thats where I have a problem figuring out how to do that. The thing I'd like to filter for is my received_signatures, which is a function that is being called in my customer.py
def received_signatures(self):
signatures = [reg.brought_signature for reg in self.registrations.all() if reg.status == '1_YES']
if len(signatures):
return all(signatures)
else:
return None
brough_signature is a DB Field
So how can I annotate the queryset, filter for the received_signatures and then return a number?
Relevant Model Information:
class Customer(models.Model):
brought_signature = models.BooleanField(u'Brought Signature', default=False)
class Registration(models.Model):
brought_signature = models.BooleanField(u'Brought Signature', default=False)
status = models.CharField(u'Status', max_length=10, choices=STATUS_CHOICES, default='4_RECEIVED')
Note: A participant and a registration can have brought_signature. I have a setting in my program which allows me to either A) mark only brought_signature at my participant (which mean he brought the signature for ALL his registrations) or B) mark brought_signature for every registration he has
For this case Option B) is relevant. With my received_signatures I check if the customer has brought every signature for every registration where his status is "1_YES" and I want to count all the customers who did so and return a number (which I then use in another function for a pygal chart)
If I understand it correctly, you want to check if all the Registrations for a given Customer with status == '1_YES should have as attribute .brought_signature = True, and there should be at least such value. There are several approaches for this.
We can do this by writing it like:
received_signatures = self.customer_set.filter(
registration__status='1_YES'
).annotate(
minb=Min('registration__brought_signature')
).filter(
minb__gt=0
).count()
So what we here do is first .filter(..) on the registrations that have as status 1_YES, next we calculate for every customer a value minb that is the minimum of brought_signature of these Registrations. So in case one of the brought_signatures of the related Registrations is False (in a database that is usually 0), then Min(..) is False as well. In case all brought_signatures are True (in a database that is usually 1), then the result is 1, we can then filter on the fact that minb should thus be greater than 0.
So Customers with no Registration will not be counted, Customers with no Registration with status 1_YES, will not be counted, Customers with Registrations for which there is a Registration with status 1_YES, but with brough_signature will not be counted. Only Customers for which all Registrations that have status 1_YES (not per se all Registrations) have brough_signature = True are counted.
I got two types of registration and can't figure out what to if by accident user selects both. Basically I want to prioritise one of the logic in case user have both the options. Following is the explanation and conditions I am trying to code.
User can register with the schools allowed to register free.
User can also register if he/she has the coupon.
If user's school is in list and user has coupon then he should be registered on behalf of university and coupon will not be used by backend.
my_school = form.university.data
waiverlist = ['A', 'B', 'C']
if my_school in waiverlist:
package = Package(
student_id=profile_data.id,
stripe_id = 'N/A For Group Subscriber',
student_email= profile_data.email,
is_active=True,
package_type='PartnerSubscription',
subscription_id='N/A For Group Subscriber'
)
dbase.session.add(package)
dbase.session.commit()
cp = Coupons.query.filter_by(coupon=Coupons.coupon).first()
if cp:
mycoupon = form.coupon.data
print mycoupon
print cp.coupon
if form.coupon.data==cp.coupon:
package = Package(
student_id=profile_data.id,
stripe_id = 'N/A For Group Subscriber',
student_email= profile_data.email,
is_active=True,
package_type='GroupSubsciption',
subscription_id='N/A For Group Subscriber'
)
dbase.session.add(package)
dbase.session.commit()
return redirect('/profile')
With above code it creates two database entries. Actually i tried with elif but couldn't make it work.
Please advise.
What about simply making the coupon check if cp and my_school not in waiverlist
Or even better make both conditional blocks of code into functions. Then call the coupon function only with a condition check that will return a call to the school function:
# I don't know what other variables you'd need, so kwargs
def register_with_coupon(school, **kwargs):
if school in waiver_list:
return register_with_school()
#insert with coupon
I have a simple one-to-many structure like this:
class User(db.Model):
userEmail = db.StringProperty()
class Comment(db.Model):
user = db.ReferenceProperty(User, collection_name="comments")
comment = db.StringProperty()
date = db.DateTimeProperty()
I fetch a user from by his email:
q = User.all() # prepare User table for querying
q.filter("userEmail =", "az#example.com") # apply filter, email lookup
results = q.fetch(1) # execute the query, apply limit 1
the_user = results[0] # the results is a list of objects, grab the first one
this_users_comments = the_user.comments # get the user's comments
How can I order the user's comments by date, and limit it to 10 comments?
You will want to use the key keyword argument of the built-in sorted function, and use the "date" property as the key:
import operator
sorted_comments = sorted(this_users_comments, key=operator.attrgetter("date"))
# The comments will probably be sorted with earlier comments at the front of the list
# If you want ten most recent, also add the following line:
# sorted_comments.reverse()
ten_comments = sorted_comments[:10]
That query fetches the user. You need to do another query for the comments:
this_users_comments.order('date').limit(10)
for comment in this_users_comments:
...