I'm new to Django and I'm trying to get the item from the database.
The problem is the item is saved as a list in Django. And item[i] is not helping either. Please help me figure it out how to get the data
in the shell, I have tried
for x in NewsItem.objects.all():
print(x.tag)
this will print
['babi kutil', 'babi hutan', 'babi liar', 'hutan indonesia']
['ibu aniaya anak']
['pilkada serentak 2018', 'bandung', 'nurul arifin', 'pilwalkot bandung 2018']
['narkoba di surabaya', 'bnnp jatim']
['pilkada serentak 2018', 'banten']
But I want to get each item, not as a list.
The NewsItem Model.
class NewsItem(models.Model):
breadcrumbs = models.CharField(max_length=150, null=True)
penulis = models.CharField(max_length=100, null=True)
judul = models.CharField(max_length=200, null=True)
berita = models.TextField()
tag = models.TextField(null=True)
url = models.CharField(max_length=200, unique = True)
website = models.CharField(max_length=50, null=True)
date = models.DateTimeField()
#property
def to_dict(self):
data = {
'data': json.loads(self.url),
'tanggal': self.tanggal
}
return data
def __str__(self):
return self.url
You can use 2 for loops to achieve this and as you have mentioned tag as TextField, so you need to split it on comma.
for x in NewsItem.objects.all():
tag_text = x.tag[1:-1]
tag_list = tag_text.split(",")
for tag in tag_list:
print(tag)
Related
I have two different models. HitCount model stores IP addresses whose was viewed Post. And what i want is filtering popular 3 posts which viewed more. I've tried some queries but i couldn't. I am sharing my models with you.
class Post(ModelMeta, models.Model):
title = models.CharField(max_length=255, verbose_name='Başlık', unique=True)
slug = models.SlugField(max_length=255, unique=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='blog_posts', verbose_name="Yazarı")
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='blog_posts',
verbose_name="Kategorisi", null=True)
tags = models.ManyToManyField(Tag, related_name='blog_posts', verbose_name='Etiketler')
image = models.ImageField(verbose_name='Fotoğraf (800x460)')
content = RichTextField()
description = models.TextField(null=True)
status = models.IntegerField(choices=STATUS, default=0, verbose_name='Yayın Durumu')
created_at = models.DateTimeField(auto_now_add=True, verbose_name='Oluşturulma Tarihi')
updated_at = models.DateTimeField(auto_now=True, verbose_name='Güncellenme Tarihi')
#property
def get_hit_count(self):
return HitCount.objects.filter(post=self).count()
class HitCount(models.Model):
ip_address = models.GenericIPAddressField()
post = models.ForeignKey("Post", on_delete=models.CASCADE)
def __str__(self):
return f'{self.ip_address} => {self.post.title}'
You can try something like this :
most_viewed_posts = Post.objects.all().order_by('-get_hit_count')[3]
I don't think that you can order by 'get_hit_count', but I think those questions can help you : Django order_by a property
Using a Django custom model method property in order_by()
I did what i want with sorted method. Thanks Alexandre Boucard for the resources.
Solution;
sorted(Post.objects.filter(status=1), key=lambda a: a.get_hit_count, reverse=True)
reverse=False as a default and it sorts ascending in this case i want to get reversed so i used reverse=True
I'm getting this error when I click on a button.
When I click the button I'm calling a function named apply.
So first of all, I've two models, JobServices and MissionEffectuee, the table MissionEffectuee is normally filled with content of JobServices.
The 2 models:
class JobServices(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) #create_user
service_name = models.CharField(max_length=100, default="nom du service")
hour = models.IntegerField(default="Heures")
amount = models.FloatField(default="Cout")
service_date = models.DateTimeField(auto_now_add=True, null=True)
description = models.CharField(max_length=2000, null=True, default="annonce")
image_url = models.CharField(max_length=2000, null=True, blank=True)
image = models.ImageField(null=True, blank=True)
class MissionEffectuee(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
service = models.ForeignKey(JobServices, on_delete=models.CASCADE, null=True)
rcd_date = models.DateTimeField(auto_now_add=True, null=True)
Here is the views methods
def apply(request, my_id):
task_applied = JobServices.objects.get(id=my_id)
task_done, failed = MissionEffectuee.objects.get_or_create(id=my_id)
if failed:
for c in task_applied:
task_done.service = c.service_name
task_done.user = c.user
print("it's saved")
task_done.save()
else:
print("Element is already there")
return redirect('../taches')
context = {'task_done': task_done}
return render(request, 'task_apply.html', context)
What I want is whenever I click on the button, service_name of the model Jobservices and user of the model User to be saved in the table MissionEffectuee in the attributes service and user respectively, but as for now, in the table these two columns are filled with hypen (-). But the rcd_date attributes normally filled as I want.
I think the problem is with the foreignkeys
You're doing a get on your JobServices model which will return 1 instance of that model.
So you need to just use that 1 instance, like this;
task_applied = JobServices.objects.get(id=my_id)
task_done, failed = MissionEffectuee.objects.get_or_create(id=my_id)
if failed:
task_done.service = task_applied # This must be a `JobServices` instance, not the name
task_done.user = task_applied.user
print("it's saved")
task_done.save()
If you used JobServices.objects.filter() then it'd return a queryset of objects from that table and you could iterate over that like you do with for c in task_applied.
Models.py
class SalesOrderItems(models.Model):
item = models.ForeignKey(MasterItems, on_delete=models.CASCADE)
item_quantity = models.IntegerField(default=0)
class SalesOrder(models.Model):
delivery_method_choice = (('Full-Truck Load', 'Full-Truck Load'), ('Part-Truck Load', 'Part-Truck Load'))
status_choices = (('On Hold', 'On Hold'),('Ready to Dispatch', 'Ready to Dispatch'),('Dispatched', 'Dispatched'))
owner = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='so_owner')
client = models.ForeignKey(MasterClient, on_delete=models.CASCADE, related_name='so_client')
reference_no = models.CharField(max_length=500, blank=True, null=True)
date = models.DateField(default=datetime.date.today)
shipment_date = models.DateField(default=datetime.date.today)
delivery_method = models.CharField(max_length=500, default='Full-Truck Load', choices=delivery_method_choice)
items = models.ManyToManyField(SalesOrderItems, related_name='items_so', blank=True, null=True)
status = models.CharField(max_length=500, default='On Hold', choices=status_choices)
origin = models.CharField(max_length=255)
destination = models.CharField(max_length=255)
I want to retrieve the items of a particular sales order by django query
My attempt to get the items:
items = []
for i in sales_orders:
so = SalesOrder.objects.filter(pk=i)[0]
print("items",so.items)
Output:
items classroom.SalesOrderItems.None
How can I get the list of items in a particular SalesOrder ??
sales_orders = SalesOrder.objects.prefetch_related('items').filter(**sales_filter_here)
for sales_order in sales_orders:
for sales_order_item in sales_order.items.all():
print(sales_order_item)
this query will work for you
SalesOrder.objects.filter(id=1).values_list('items__item__item_name')
below is my simple Masteritems model
class MasterItems(models.Model):
item_name = models.CharField(max_length=50)
def __str__(self):
return self.item_name
by this way you will get every item name in queryset. this is my simple output
<QuerySet [('rice',), ('pepsi',), ('Computer',)]>
I want to create a custom object list in the view and pass it to the template. In the template I want to loop over the list and display the information.
My models are
class CustomUser(AbstractUser):
def __str__(self):
return self.email
class Post(models.Model):
author = models.ForeignKey(CustomUser,on_delete=models.CASCADE,)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
post_url = models.URLField(max_length = 200, blank = True)
slug = models.SlugField(unique=True, blank=True)
class subscription(models.Model):
creator = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='creator',)
booster = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='booster')
sub_value = models.FloatField(blank = True)
sub_id = models.TextField(blank = True)
status = models.BooleanField(default=False)
dateSubscribed = models.DateTimeField(default=timezone.now)
dateSubscriptionEnded = models.DateTimeField(default=timezone.now)
paymentCount = models.FloatField(default= 0)
I want to filter objects from subscription model like below
subs = subscription.objects.filter(booster = request.user)
Then find creators in the above subs object list and for each creator get the name, numbers Posts, and number of Subscribers. Add this to custom list and pass it to the template to loop over and display the information in the template. Can someone help me how to create this custom list. Thanks!
Ok so here are the basics minus the subscribers because I don't see the relation clearly. This is how to parse the name and the number of posts. \
my_list = []
for sub in subs:
name = sub.creator.name
auth_id = sub.creator.id
posts = Post.objects.filter(author=auth_id)
num_of_posts = len(posts)
my_list.append({
'name':name,
'post_count': num_of_posts,
})
then you would pass mylist thru the template context.
It is a common mistake to name the related_name=… parameter [Django-doc] to the same value as the name of the field. The related_name parameter however is the name of the reverse relation Django will automatically add. So here it means a relation to access for example the related subscription objects of a given CustomUser.
Therefore it makes more sense to rename these, for example like:
class Subscription(models.Model):
creator = models.ForeignKey(
CustomUser,
default=None,
null=True,
on_delete=models.CASCADE,
related_name='created_subscriptions'
)
booster = models.ForeignKey(
CustomUser,
default=None,
null=True,
on_delete=models.CASCADE,
related_name='boosted_subscriptions'
)
sub_value = models.FloatField(blank=True)
sub_id = models.TextField(blank =True)
status = models.BooleanField(default=False)
dateSubscribed = models.DateTimeField(default=timezone.now)
dateSubscriptionEnded = models.DateTimeField(default=timezone.now)
paymentCount = models.FloatField(default=0)
Next we can make a query where:
from django.db.models import Count
CustomUser.objects.filter(
created_subscriptions__booster=request.user
).annotate(
number_of_posts=Count('post', distinct=True)
)
This is a QuerySet of CustomUsers where each CustomUser that arises from this QuerySet has an extra attribute .number_of_posts that contains the number of posts. You thus can iterate over the queryset directly in the template.
I am making a very lightweight crm for a non-profit, in django. The models of interest to this problem are:
class Human(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
nickname = models.CharField(max_length=200, blank=True, null=True)
middle_name = models.CharField(max_length=200, blank=True, null=True)
def __unicode__(self):
namestring = self.last_name+','+self.first_name
if self.nickname:
namestring += '('+self.nickname+')'
elif self.middle_name:
namestring += '('+self.middle_name+')'
return namestring
class PhoneNumber(models.Model):
humans = models.ManyToManyField(Human, through='HumanToPhoneNumber')
nation_code = models.IntegerField(blank=True, null=True)
area_code = models.IntegerField()
local_number = models.IntegerField()
def __unicode__(self):
what_to_call_it = "("+str(self.area_code)+")"+str(self.local_number)
if (self.nation_code):
what_to_call_it = str(self.nation_code)+what_to_call_it
return what_to_call_it
class HumanToPhoneNumber(models.Model):
human = models.ForeignKey(Human)
phone_number = models.ForeignKey(PhoneNumber)
begin_date = models.DateTimeField('begin date')
end_date = models.DateTimeField('end date', null=True, blank=True)
active = models.BooleanField(default=True)
preferred = models.BooleanField(default=False)
label = models.CharField(max_length=200, blank=True, null=True)
def __unicode__(self):
what_to_call_it = str(self.human)
if self.label:
what_to_call_it += "("+self.label+")"
return what_to_call_it
When I show the phone numbers for a person, I only want to show the ones that are still "active", and also display a marker by the preferred method of contact (there are similar models for email, humantoemail, address, humantoaddress). More than one person can have the same number, and a person can have multiple numbers, so it's many-to-many.
The view for this is:
def human(request, human_id):
p = get_object_or_404(Human, pk=human_id)
emails = p.emailaddress_set.all()
emails.filter(emailaddress__humantoemailaddress.active=True) #this line does not work
phone_numbers = p.phonenumber_set.all()
addresses = p.physicaladdress_set.all()
return render_to_response('person.html', {'person': p, 'emails': emails, 'phone_numbers': phone_numbers, 'addresses': addresses})
I've tried a few variations on the above, but I'm clearly not groking how I'm meant to access the "active" field on the many-to-many relationship. I can't put the field on the Email, PhoneNumber, or PhysicalAddress model because it could be still active for one person but no longer active for another, and similarly for "preferred".
What is the right way to write this query in a django view? Any help is appreciated. Oh, and I'm using Django 1.3, in case that matters.
Edit: corrected a typo in the above, plus tried a different filter on phone number copied more or less exactly from Django docs on MTM:
def human(request, human_id):
p = get_object_or_404(Human, pk=human_id)
emails = p.emailaddress_set.filter(humantoemailaddress__active=True) <--- does not work
phone_numbers = p.phone_number_set.filter(humantophonenumber__begin_date__gt=date(2011,1,1)) <--- does not work either
addresses = p.physicaladdress_set.all()
return render_to_response('person.html', {'person': p, 'emails': emails, 'phone_numbers': phone_numbers, 'addresses': addresses})
Any help is appreciated, and let me know if there's any other details I should be adding.
Second Edit: D'oh! It helps to edit the right file. I have checked the answer below, which actually works just fine.
You can filter on fields in the joining table using double underscore notation e.g. humantophonenumber__active.
For example:
p = get_object_or_404(Human, pk=human_id)
phone_numbers = p.phone_number_set.filter(humantophonenumber__active=True)
For further Beatles-based examples, check out the Django docs.