query ForeignKey of model - python

**I want get all orders of customer whose id = 3 **
----------------------------------------------------------------
class customer(models.Model):
name = models.CharField(max_length=200,null= True)
phone = models.CharField(max_length=200,null= True)
email = models.CharField(max_length=200,null= True)
date_created = models.DateTimeField(auto_now_add=True,null=True)
def __str__(self):
return self.name
class order(models.Model):
STATUS = (
('pending','pending'),
('out for delivery','out for delivery'),
('deliveried','deliveried')
)
date_created = models.DateTimeField(auto_now_add=True,null=True)
status = models.CharField(max_length = 200 , null=True,choices=STATUS)
customer= models.ForeignKey(customer,null=True,on_delete=models.SET_NULL)
product = models.ForeignKey(product,null=True,on_delete=models.SET_NULL)

There are two possible ways to do it.
One way is from order objects:
order.objects.filter(customer__id=3)
Second from customer objects:
customer.objects.get(id=3).order_set.all()

its actually quite simple.
just do the following
order.objects.filter(customer_id=3)

you can use the filter method provided by Django model class
This method returns all the orders in a query-set object.
so one more question might raise is where we should actually use this method?
You can actually do this in your views.py
Example:
urls.py
path('my_view/<int:id>',views.my_order,name="my_order")
views.py
def my_order(request,id):
my_orders = order.objects.filter(customer_id=3) #this will return a query set
return render(request,'index.html',{'my_orders':my_orders})
index.html
<body>
{% for o in my_orders %}
{{o}}
{% endfor %}
</body>

Related

how to show my post only to my friends in django

I want to show my post only to my friends, How can I filter my post only to my friends? I have tried to filter in html code but as my friends get more, it repeats my post more (I mean repeat one post few times )
My models.py
class PostUser(models.Model):
posttype = models.CharField(max_length=3000, default='postuser')
content = models.TextField(null = True, blank= True)
media_image = models.FileField(null = True, blank= True)
media_video = models.FileField(null = True, blank= True)
per_to = models.CharField(max_length=300, null=True, blank=True, default='everyone')
status = models.CharField(max_length=3000, default='active')
date = models.DateField(auto_now_add=True)
time = models.TimeField(auto_now_add=True)
datetime = models.DateTimeField(auto_now_add=True)
like = models.IntegerField(null=True, blank=True)
comment = models.IntegerField(null=True, blank=True)
share = models.IntegerField(null=True, blank=True)
user_pk = models.IntegerField()
class Friends(models.Model):
# Sender
friend_one = models.IntegerField()
# Reciver
friend_two = models.IntegerField()
per_to = models.CharField(max_length=300, null=True, blank=True, default='everyone')
status = models.CharField(max_length=3000, default='active')
datetime = models.DateTimeField(auto_now_add=True)
date = models.DateField(auto_now_add=True)
time = models.TimeField(auto_now_add=True)
and this is my views.py
allmyfriends = Friends.objects.filter(Q(friend_one = request.user.pk) | Q(friend_two = request.user.pk))
You can do it like :-
models.py
Choices = (
(True,'Friends can see Post'),
(False,'Friends cannot see Post'),
)
class Friends(models.Model):
...................
only_friends = models.BooleanField(max_length=30,choices=Choices,default=True)
Accessing Friends model objects in views Because our BooleanField is in Friends model so we have to access Friends model first to access only_friends BooleanField
def some_view(request,user_id):
allmyfriends = get_object_or_404(Friends,user_user_id)
p = request.user
you = p.user
friends = p.friends.all()
context = {'allmyfriends':allmyfriends,'friends':friends}
return render(request, 'mains:your_template.html', context}
urls.py
path('some_view/<int:user_id>/',views.some_view,name='some_view'),
your_template.html
Now do work carefully here.
In showing post, I assume that you're using loop for showing all of users Post. like :-
{% for posts in post %}
{% if posts.user.only_friends == True and posts.user in request.user.friends.all %}
{{ post.posttype }}
{% endif %}
{% endfor %}
Note :- This FrontEnd will only work after you set your PostUser ForeignKey relationship with User like :-
from django.contrib.auth.models import User
class PostUser(models.Model):
..................
user = models.ForeignKey(User,on_delete=models.CASCADE,default='',unique=True)
Also Set your Friends model ForeignKey RelationShip with User
class Friends(models.Model):
.............
user = models.ForeignKey(User,on_delete=models.CASCADE,default='',unique=True)
Explanation :-
In models.py :- I add a BooleanField with Choices.
In views.py :- I access Friends model to access its objects with user_id. ( Check carefully in template urls while using user_id )
In template :- I use a for loop to show all the Posts. AND In for loop i started if statement that If the user who posted a post is in request.user's friends and have BooleanField True then Post will show and if request.user isnot in posted user then the post will not be shown.
#Ramin Zamani- Your friend model is messed up. Have a look at this.
Rename your model Friends to UserFriend. It's a model that shows the relation between 2 entities - The user and his/her friends/followers. The model name shouldn't be plural.
from django.conf import settings
class UserFriend(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
friend = models.ForeignKey(settings.AUTH_USER_MODEL)
................
Also, I could have used a many-to-many relation but I prefer the foreign key relation. It's up to your preference.
Your post model needs to be fixed
class Post(models.Model):
created_by= models.ForeignKey(settings.AUTH_USER_MODEL)
...............
And if you want only specific users to let's say view a post then you can do the following.
in your views.py
post = Post.objects.get(slug=self.kwargs.get('name'))
#to check if the user trying to access the post is a friend of the postcreator user.
friend = UserFriend.objects.get(user=post.created_by,friend=self.request.user)
if friend:
render()
else:
return HttpResponseForbidden()

Django Show Unique List Of Subjects (Many To Many) In Dropdown Menu

I want to be able to produce a dropdown menu in my template with a unique list of subjects.
Subjects are populated inside of admin rather than hard coding them in SUBJECT_CHOICES.
A course can have many subjects or only 1 subject. For example:
Course Title = Django
Subject = Technology
Course Title = Python
Subject = Technology
Course Title = Accounting
Subject = Business
Course Title = E-commerce
Subject(s) = Technology, Business
CourseListView corresponds to the course_list.html template.
models.py:
class Subject(models.Model):
SUBJECT_CHOICES = ()
name = models.CharField(max_length=20,choices=SUBJECT_CHOICES, unique=True)
def __str__(self):
return self.name
class Course(models.Model):
​
SKILL_LEVEL_CHOICES = (
('Beginner', 'Beginner'),
('Intermediate', 'Intermediate'),
('Advanced', 'Advanced'),
)
​
slug = models.SlugField()
title = models.CharField(max_length=120)
description = models.TextField()
allowed_memberships = models.ManyToManyField(Membership)
created_at = models.DateTimeField(auto_now_add=True)
subjects = models.ManyToManyField(Subject)
skill_level = models.CharField(max_length=20,choices=SKILL_LEVEL_CHOICES, null=True)
visited_times = models.IntegerField(default=0)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('courses:detail', kwargs={'slug': self.slug})
#property
def lessons(self):
return self.lesson_set.all().order_by('position')
​
views.py:
class CourseListView(ListView):
model = Course
def get_queryset(self):
qs = super().get_queryset()
title_contains_query = self.request.GET.get('title_contains')
view_count_min = self.request.GET.get('view_count_min')
view_count_max = self.request.GET.get('view_count_max')
date_min = self.request.GET.get('date_min')
date_max = self.request.GET.get('date_max')
skill_level_query = self.request.GET.get('skill_level')
if title_contains_query:
qs = qs.filter(title__icontains=title_contains_query)
if view_count_min:
qs = qs.filter(visited_times__gte=view_count_min)
if view_count_max:
qs = qs.filter(visited_times__lte=view_count_max)
if date_min:
qs = qs.filter(created_at__gte=date_min)
if date_max:
qs = qs.filter(created_at__lte=date_max)
if skill_level_query:
qs = qs.filter(skill_level=skill_level_query)
return qs
Desired Output:
I tried writing a for loop in my template that does return the subjects successfully but they are not unique or showing only once.
{% for item in object_list %}
<h2>{{ item.subjects.all}}</h2>
<ul>
{% for sub in item.subjects.all %}
<li>{{ sub.name }}</li>
{% endfor %}
</ul>
{% endfor %}
​
Result:
​
<QuerySet [<Subject: Business>]>
Business
<QuerySet [<Subject: Technology>]>
Technology
<QuerySet [<Subject: Technology>]>
Technology
<QuerySet [<Subject: Business>]>
Business
I would prefer to do it with a for loop that produces unique results, but maybe it can be done with django-select2 or use a form with model select or multiple model select? Can someone provide some code for either the loop or one of these methods?
I would appreciate any help with this.
I see two solutions here:
The first one if to simply get all the entered values in the Subject model but you couldn't use all the filters you are using in your view, only the one about the title.
To do so, just use:
title_contains_query = self.request.GET.get('title_contains')
if title_contains_query:
subjects = [title for title in Subject.objects.filter(title__icontains=title_contains_query)]
The other option is to use the distinct() method on your QuerySet which filters and remove the duplicate entries in it. Use it like this: qs = qs.distinct()
Hope it helps!

trying to truncate column content in django_table2

I have a django table with a column that has decimal points upto 7 points. The column is called error. Can anyone help me truncate the data to only two decimal points or maybe round the number?
model:
class Course (models.Model):
null_value = 0
department = models.CharField(max_length=200)
course = models.CharField(max_length=200)
semester = models.CharField(max_length=200)
actual = models.FloatField (default=0)
prediction = models.FloatField(default=0)
error = models.FloatField(default=0)
table
class NameTable(tables.Table):
# actions = tables.Column(orderable=False)
# selection = tables.CheckBoxColumn(accessors="pk", orderable = False)
# table = n_object.filter(course=course_selected).order_by('id').all()
table=tables.Table
# actual1 = table.values_list('actual')
error = tables.Column(verbose_name='ERROR (%)')
class Meta:
model = Course
fields = ("semester","actual","prediction","error")
order_by_field = True
whats in the view (i modified it to what you guys need):
def report_table1(request):
n_object = Department.objects.all()
table = n_object.filter(department=department_selected).order_by('id').all()
t_data = NameTable(table)
RequestConfig(request).configure(t_data)
return render(request, 'table.html', {"table_course": t_data})
html file
{% block content %}
{% load render_table from django_tables2 %}
<div style="text-align: center;">
<!--<h2>Prediction for all Courses</h2>-->
<!--<table style="width: 100%;" "text-align:center;">-->
{% render_table table_course%}
<!--</table>-->
{% endblock %}
what should I do? I would prefer to round the number in the error column
Another solution you can use:
class NameTable(tables.Table):
def render_error(self, **kwargs):
return round(kwargs['value'], 2)
# or you can return like markdesign's answer :)
#return u"%.2f" % (kwargs['value'])
class Meta:
model = Course
fields = ("semester","actual","prediction","error")
order_by_field = True
Here is a simple solution, you can round your data using a simple trick. You should create a property inside your model that defines a rounded value for your error record. Let's see the code (it should work but I can't test it right now):
Model:
class Course (models.Model):
null_value = 0
department = models.CharField(max_length=200)
course = models.CharField(max_length=200)
semester = models.CharField(max_length=200)
actual = models.FloatField (default=0)
prediction = models.FloatField(default=0)
error = models.FloatField(default=0)
#property
def roundedError(self):
return u"%.2f" % (self.error)
# or you can return like ruddra's answer ;)
# return round(self.error, 2)
Table:
class NameTable(tables.Table):
...
roundedError = tables.Column()

Django template sort by 'unrelated' model's field

I'm trying to sort related items in a template by a field in a model three ForeignKey relationships away. I'm assembling the data for the template in the view as proposed in another StackOverflow answer:
Sorting related items in a Django template
As far as I can tell, I copied the code from this as-is except for I had to change variable names. It doesn't throw an error, it just displays no list items in the HTML unordered list.
# checkout.html
{% for item in cart_items %}
<tr>
<td class="left">
{{ item.name }}
<ul>
{% for part in part_list %}
<li>{{ part.name }}
{% endfor %}
</ul></td>
</tr>
{% endfor %}
And the view...
# views.py
def checkout(request):
cart_items = get_cart_items(request)
itemCollection = []
for item in cart_items:
item.part_list = item.product.buildpart.all().order_by('product__family__type')
itemCollection.append(item)
return render(request, 'checkout.html', locals())
And the get_cart_items function:
# cart.py
def get_cart_items(request):
""" return all items from the current user's cart """
return CartItem.objects.filter(cart_id=get_cart_id(request))
As I said, the template and view are pretty much copies of the solution presented in the aforementioned StackOverflow article. One thing I thought was curious was that itemCollection[] from the view is never referenced in the template.
I believe the order_by clause ('product__family__type') is right only because it doesn't generate an error. But in case that is the problem or a part of it here is the chain of models I am attempting to navigate in that order_by clause:
We start from the shopping cart model (CartItem):
class Item(models.Model):
cart_id = models.CharField(max_length=50)
quantity = models.IntegerField(default=1)
product = models.ForeignKey(PartModel, unique=False)
class Meta:
abstract = True
class CartItem(Item):
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['date_added']
verbose_name = "Cart Item"
Through the 'product' field we get to the model holding our inventory and its self-referential BuildPart ManyToMany model:
class PartModel(models.Model):
family = models.ForeignKey(PartFamily)
name = models.CharField("Model Name", max_length=50, unique=True)
buildpart = models.ManyToManyField('self', through='BuildPart',
symmetrical=False, related_name='+')
class Build(models.Model):
build = models.ForeignKey(PartModel, related_name='+')
part = models.ForeignKey(PartModel, related_name='+')
quantity = models.PositiveSmallIntegerField(default=1)
class Meta:
abstract = True
unique_together = ('build', 'part')
def __unicode__(self):
return self.build.name + ' with ' + str(self.quantity) + ' * ' + \
self.part.family.make.name + ' ' + self.part.name
class BuildPart(Build):
pass
class Meta:
verbose_name = "Build Part"
From there we follow the 'family' field to the PartFamily model:
class PartFamily(models.Model):
make = models.ForeignKey(PartMake)
type = models.ForeignKey(PartType)
name = models.CharField("Family Name", max_length=30,
unique=True)
slug = models.SlugField(unique=True)
And lastly, we get to the model with the 'order' field, the one we wish to sort the related items by, PartType:
class PartType(models.Model):
name = models.CharField("Part Type", max_length=30, unique=True)
slug = models.SlugField(unique=True)
order = models.PositiveSmallIntegerField()
description = models.TextField(blank=True, null=True)
To recap, how do I get the shopping cart products' related items, and sort them by the 'order' field in the PartType model?
You have two errors, both in the template.
Firstly, you've put your items with the sorted relationship in a list called itemCollection, but in the template you're iterating over cart_item instead. This is a very good example of why you should be explicit about what variables you pass to the template, rather than relying on locals().
Secondly, you then iterate over part_list without defining it. You mean item.part_list.

Django showing in a template a ManytoManyField that is into a Dictionary

The thing is quite simple but i don't know how to do it.
I got the next models.py
class ElementoDeRed(models.Model):
IP_Address = models.CharField(max_length=200, primary_key= True)
MAC_Address = models.CharField(max_length=200)
offset_bytes = models.CharField(max_length=200)
transfered_bytes = models.CharField(max_length=200)
time = models.CharField(max_length=200)
previous_bytes = models.CharField(max_length=200)
previous_previous_bytes = models.CharField(max_length=200)
class Meta:
verbose_name = 'Dispositivos en mi nube'
verbose_name_plural = 'Dispositivos en mi nube'
def __unicode__ (self):
return smart_unicode(self.IP_Address)
class Register(models.Model):
user = models.ForeignKey(User)
network_element = models.ManyToManyField(ElementoDeRed)
registered_date = models.DateTimeField(null=True,blank=True)
def __unicode__ (self):
#return smart_unicode(self.network_element)
return smart_unicode("%s: %s" % (self.user,self.network_element.all()[0]))
As you can see, Register is using a ElementoDeRed element to storage on itself.
The thing is that i want to show in my template something like :
"The user <'user'> has the next device configured with this IP : <'IP_Address'>, Mac: <'Mac_Address'> ...."
What I am rendering on the template is a var called "dict_username_registers", is a dictionary witch key value is the username and the items asocciate to it are the "registers" fields.
But im getting something like :
david: [<Register: david: 10.0.0.3>, <Register: david: 10.0.0.1>] , Alice: <Register: Alice: 10.0.0.2>]
How can i access to that field in HTML????
Thank you! Let me know if u need something else!
you can iterate over the elements of dict_username_registers like this
{% for register in dict_username_registers %}
accessing date {{register.registered_date}}
{% endfor %}
you car read more about those tags here

Categories

Resources