Re: Optimized Query

2020-05-28 Thread אורי
Hi Soumen,

Sometimes prefetch_related is much faster and more efficient than
select_related. I usually prefer to use prefetch_related.

Uri.
אורי
u...@speedy.net


On Thu, May 28, 2020 at 12:42 AM Soumen Khatua 
wrote:

> Actually I want to fetch all users from User table and users location from
> Location table which is many to many relation from same Profile table. Is
> it possible???
>
> On Thu 28 May, 2020, 2:54 AM Soumen Khatua, 
> wrote:
>
>> Now I'm facing one problem whenever I'm trying to iterate a loop I'm
>> getting too many SQL variables. Actually after iterating the loop I want to
>> render all the value in the template.
>> if could you resolve this it would be very good for me.
>> Thank you for your time and response
>>
>> Regards,
>> Soumen
>>
>>
>> On Thu, May 28, 2020 at 2:12 AM Chetan Ganji 
>> wrote:
>>
>>>
>>> Profile.objects.filter().select_related("user").prefetch_related("location")
>>>
>>> On Thu, May 28, 2020, 2:01 AM Soumen Khatua 
>>> wrote:
>>>
 I also know about this concept but I don't how I can achieve it, Could
 you give me an example?
 Suppose I have:







 *class Profile(models.Model):user = models.OneToOneField(
 settings.AUTH_USER_MODEL,on_delete = models.CASCADE,
 related_name="profile")location = models.ManyToManyField(Location)*


 Thank you

 Regards,
 Soumen

 On Wed, May 27, 2020 at 7:20 PM Chetan Ganji 
 wrote:

> select_related for fk and prefetch_related for m2m in django, you can
> chain them together
>
> Regards,
> Chetan Ganji
> +91-900-483-4183
> ganji.che...@gmail.com
> http://ryucoder.in
>
>
> On Wed, May 27, 2020 at 4:51 PM Soumen Khatua <
> soumenkhatua...@gmail.com> wrote:
>
>> Hi Folks,
>> I have many to many relationships and Foreign Key in the table, I'm
>> using select_realted(foreign key filed name) to optimize the query but I
>> want to fetch many to many and foreign key at the same time , How I can 
>> do
>> this in very optimized way?
>>
>> Thank You
>> Regards,
>> Soumen
>>
>> --
>> You received this message because you are subscribed to the Google
>> Groups "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it,
>> send an email to django-users+unsubscr...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-users/CAPUw6Wb6f-BCwUZfvgzGtsrbV1seq1iGbXyuqoH%3DKxZrJ2EyLg%40mail.gmail.com
>> 
>> .
>>
> --
> You received this message because you are subscribed to the Google
> Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CAMKMUju19j7apa1pXZQcZTY-6ThTJC%3DAL2eQhtO7DL2oTk6Oog%40mail.gmail.com
> 
> .
>
 --
 You received this message because you are subscribed to the Google
 Groups "Django users" group.
 To unsubscribe from this group and stop receiving emails from it, send
 an email to django-users+unsubscr...@googlegroups.com.
 To view this discussion on the web visit
 https://groups.google.com/d/msgid/django-users/CAPUw6WZXtTJssu6SwO8_BiTDxDnzJtKYy9j1hQsMR74jKYC6aA%40mail.gmail.com
 
 .

>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-users+unsubscr...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-users/CAMKMUjth%3DNm%2BUa74bz1PiRYFGhKU-PER9_Y_XQdHRQ23KMbp7Q%40mail.gmail.com
>>> 
>>> .
>>>
>> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CAPUw6WY0T5U10NpzTXcsmdsvx641cdDiYJaU%2B3DEjzmb3iPDEA%40mail.gmail.com
> 

Re: filter on multiple tables

2020-05-28 Thread אורי
Hi Soumen,

You can filter on another table by using __, for example:

User.objects.filter(profile__profiles__institute_name="Example")

Or:

User.objects.filter(profile__profiles__institute_name__in=["Example 1",
"Example 2"])
אורי
u...@speedy.net


On Thu, May 28, 2020 at 11:27 PM Soumen Khatua 
wrote:

> Actually I want to filter all users those are matched with currently
> logged in users based on location or education details like maybe
> institute_name or specialization. Is it possible to search in multiple
> tables?!
> I almost spent 2 days but still I stuck in the position.
> Any help would be appreciated.
>
> Thank You
>
> Regards,
> Soumen
>
>
>
>
> *class Location(models.Model):name = models.CharField(max_length = 15)*
>
>
>
>
>
>
>
> *class Profile(models.Model):user = models.OneToOneField(
> settings.AUTH_USER_MODEL,on_delete = models.CASCADE,
> related_name="profile")location =
> models.ManyToManyField(Location,related_name = 'user_locations')*
>
>
>
>
> *class Education(models.Model):profile = models.ForeignKey(Profile,
> on_delete=models.CASCADE,related_name="profiles")institute_name =
> models.CharField(max_length = 250)specialization =
> models.CharField(max_length = 100)*
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CAPUw6WZqX9oqutYfGJqAwCswY_00VfTmf624ypypAr6saS61Nw%40mail.gmail.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CABD5YeFfHWDEkTFwMFocApuG3ejYY5QjqHHd_86wNNc-JoWP4g%40mail.gmail.com.


Re: how to use **kwargs if filters contains list of values

2020-05-28 Thread Manvi Tyagi

Yes Andreas Kuhne, I ultimately went with something like this only!!
Thanks for the reply.


On Thursday, May 28, 2020 at 5:37:33 PM UTC+5:30, Andréas Kühne wrote:
>
> Simply put - you can't. not without if statements.
>
> What I would do is something like this:
>
> query = Q()
>
> for item in kwargs.items():
>   if isinstance(item[1], list):
> query &= Q(**{f"{item[0]}__in": item[1]})
>   else:
> query &= Q(**{item[0]: item[1]})
>
> query_set = query_set.filter(query)
>
> Regards,
>
> Andréas
>
>
> Den tors 28 maj 2020 kl 12:45 skrev Manvi Tyagi  >:
>
>> i have a dict of filters , 
>> something like
>>
>> {
>> "name": "string",
>> "status": [
>>   "A", "B"
>> ],
>> "reg": "string",
>> "oc": [
>>   "As","jb"
>> ]
>>   }
>>
>>
>> ```query_set = query_set.filter(**filters)``` This works fine for all 
>> the filters whose type is not list , How do apply the filters on list 
>> values? 
>> PS: I know about __in know I can do something like 
>>   # if status_list:
>> # query_set = query_set.filter(status__in=status_list)
>>
>> BUT , 
>> 1. I dont want to use if else statemnets
>> 2. I want to have dynamic variables in the filters arguments and not 
>> hardcore ones like status__in
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django...@googlegroups.com .
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/47e6ae26-82c9-433c-8de3-08b303004864%40googlegroups.com
>>  
>> 
>> .
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/a2fb9e0c-1c8b-46b4-a7f5-ac801a67ed37%40googlegroups.com.


Templates vs. source code

2020-05-28 Thread אורי
Django users,

There was a discussion in Stack Overflow related to an answer of mine - how
to access settings from templates in Django [
https://stackoverflow.com/a/53953578/1412564]. And I would like to know -
is it generally unsafe to expose all my settings to templates and why?
Should I use the updated answer and expose only specific settings to
templates? Because if a hacker can change my templates, they can also
change my .py files, and then they can give themselves any access they want
to. So what is better - expose all my settings to templates or only
specific settings which I consider safe?

Thanks,
Uri.
אורי
u...@speedy.net

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CABD5YeEmHtPHMKs7ub42eeTQR8_XfDUGwyCtn9XGmvZ0JyFfwQ%40mail.gmail.com.


How models.Manager is working behind the scene and calling different serialize methods?

2020-05-28 Thread django-newbie
Hi, 
I am new to django and going through a tutorial and now confused with one 
particular implementation.

models.py

import json
from django.core.serializers import serialize

from django.db import models
from django.conf import settings

# Create your models here.


def upload_update_image(instance, filename):
return "updates/{owner}/{filename}".format(owner=instance.owner, 
filename=filename)

class UpdateQuerySet(models.QuerySet):
 
def serialize(self):
print("UpdateQuerySet serialize")
print(self.values("owner", "content", "image"))
list_values = list(self.values("owner", "content", "image"))
return json.dumps(list_values)


class UpdateManager(models.Manager):

def get_queryset(self):
print('get_queryset method')
return UpdateQuerySet(self.model, using=self._db)


class BasicUserUpdate(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
content = models.TextField(blank=True,null=True)
image = 
models.ImageField(blank=True,null=True,upload_to=upload_update_image,)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.content or ''

objects = UpdateManager()


def serialize(self):
print("BasicUserUpdate serialize")
try:
image = self.image.url
except:
image = ""
data = {
"content": self.content,
"owner": self.owner.id,
"image": image
}
data = json.dumps(data)
return data

  
views.py

from basic.models import BasicUserUpdate
from django.views import View
from django.http import HttpResponse


class BasicUserUpdateListView(View):
def get(self, request, *args, **kwargs):
qs = BasicUserUpdate.objects.all()
json_data = qs.serialize()
return HttpResponse(json_data, content_type='application/json')

class BasicUserUpdateDetailView(View):

def get(self, request,id, *args, **kwargs):
qs = BasicUserUpdate.objects.get(id=id)
json_data = qs.serialize()
return HttpResponse(json_data, content_type='application/json')

]


*At run time calling ListView, get below print messages*
get_queryset method
UpdateQuerySet serialize

*At run time calling DetailView, get below print messages*
get_queryset method
BasicUserUpdate serialize


*How Django is identifying which serialize method to be called? *

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/3fdc04cb-5da9-4d6a-8935-3ebf9409196b%40googlegroups.com.


filter on multiple tables

2020-05-28 Thread Soumen Khatua
Actually I want to filter all users those are matched with currently logged
in users based on location or education details like maybe institute_name
or specialization. Is it possible to search in multiple tables?!
I almost spent 2 days but still I stuck in the position.
Any help would be appreciated.

Thank You

Regards,
Soumen




*class Location(models.Model):name = models.CharField(max_length = 15)*







*class Profile(models.Model):user = models.OneToOneField(
settings.AUTH_USER_MODEL,on_delete = models.CASCADE,
related_name="profile")location =
models.ManyToManyField(Location,related_name = 'user_locations')*




*class Education(models.Model):profile = models.ForeignKey(Profile,
on_delete=models.CASCADE,related_name="profiles")institute_name =
models.CharField(max_length = 250)specialization =
models.CharField(max_length = 100)*

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAPUw6WZqX9oqutYfGJqAwCswY_00VfTmf624ypypAr6saS61Nw%40mail.gmail.com.


Re: Migration dependency not added when field is altered

2020-05-28 Thread Erin Masatsugu
I understand that -- my question is why the AlterField operation in this 
case didn't add a migration dependency.

On Wednesday, May 27, 2020 at 6:44:16 PM UTC-10, Durai pandian wrote:
>
> When you make any changes to the field, AlterField will be added rather 
> than AddField.
>
> On Thu, May 28, 2020 at 7:32 AM Erin Masatsugu  > wrote:
>
>> If I have this a model in app A:
>> class AppAModel(models.Model):
>> name = models.CharField(max_length=50, default="")
>>
>> and this model in app B:
>> class AppBModel(models.Model):
>> name = models.CharField(max_length=50, default="")
>>
>> and a I add a foreign key to AppAModel in app C:
>> class AppCModel(models.Model):
>> my_field = models.ForeignKey(AppAModel, on_delete=models.CASCADE)
>>
>> the generated migration file correctly adds a dependency from app C to 
>> app A:
>> class Migration(migrations.Migration):
>>
>> dependencies = [
>> ('app_a', '_app_a_migration'),
>> ('app_c', '_app_c_migration'),
>> ]
>>
>> operations = [
>> migrations.CreateModel(
>> name='AppCModel',
>> fields=[
>> ('id', models.AutoField(auto_created=True, 
>> primary_key=True, serialize=False, verbose_name='ID')),
>> ('my_field', 
>> models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, 
>> to='ncm.AppAModel')),
>> ],
>> ),
>> ]
>>
>> However, if I then update my_field to instead have a foreign key to 
>> AppBModel, django doesn't add a migration dependency from app C to app B:
>> class Migration(migrations.Migration):
>>
>> dependencies = [
>> ('app_c', '_app_c_migration'),
>> ]
>>
>> operations = [
>> migrations.AlterField(
>> model_name='appcmodel',
>> name='my_field',
>> 
>> field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, 
>> to='metals.AppBModel'),
>> ),
>> ]
>>
>> I saw the response here 
>> https://groups.google.com/forum/#!searchin/django-users/migration$20dependency%7Csort:date/django-users/-h9LZxFomLU/ry_yeWGfDQAJ
>>  
>> so I don't believe this is expected behavior, but can someone confirm?
>>
>> Thank you!
>> Erin
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django...@googlegroups.com .
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/48ab3732-f667-472f-a678-ca9f082315da%40googlegroups.com
>>  
>> 
>> .
>>
>
>
> -- 
> Thanks & Regards,
>
>
> *Durai pandianMobile  : +91-9611051220Email: ddp...@gmail.com 
>  *
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/70b206b3-fec7-4d0d-ae29-5ae07eef53d5%40googlegroups.com.


Re: how to use **kwargs if filters contains list of values

2020-05-28 Thread Andréas Kühne
Simply put - you can't. not without if statements.

What I would do is something like this:

query = Q()

for item in kwargs.items():
  if isinstance(item[1], list):
query &= Q(**{f"{item[0]}__in": item[1]})
  else:
query &= Q(**{item[0]: item[1]})

query_set = query_set.filter(query)

Regards,

Andréas


Den tors 28 maj 2020 kl 12:45 skrev Manvi Tyagi :

> i have a dict of filters ,
> something like
>
> {
> "name": "string",
> "status": [
>   "A", "B"
> ],
> "reg": "string",
> "oc": [
>   "As","jb"
> ]
>   }
>
>
> ```query_set = query_set.filter(**filters)``` This works fine for all the
> filters whose type is not list , How do apply the filters on list values?
> PS: I know about __in know I can do something like
>   # if status_list:
> # query_set = query_set.filter(status__in=status_list)
>
> BUT ,
> 1. I dont want to use if else statemnets
> 2. I want to have dynamic variables in the filters arguments and not
> hardcore ones like status__in
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/47e6ae26-82c9-433c-8de3-08b303004864%40googlegroups.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAK4qSCeXR_gD7HLQeYGNZ3q2OTfV7WkdTmJA1VmN_X0wszu9Cw%40mail.gmail.com.


how to use **kwargs if filters contains list of values

2020-05-28 Thread Manvi Tyagi
i have a dict of filters , 
something like

{
"name": "string",
"status": [
  "A", "B"
],
"reg": "string",
"oc": [
  "As","jb"
]
  }


```query_set = query_set.filter(**filters)``` This works fine for all the 
filters whose type is not list , How do apply the filters on list values? 
PS: I know about __in know I can do something like 
  # if status_list:
# query_set = query_set.filter(status__in=status_list)

BUT , 
1. I dont want to use if else statemnets
2. I want to have dynamic variables in the filters arguments and not 
hardcore ones like status__in

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/47e6ae26-82c9-433c-8de3-08b303004864%40googlegroups.com.


Re: Can we use python related api's on the Django templates ?

2020-05-28 Thread Derek
While you cannot use Python operators and functions directly in the 
templates, you can write your own "wrappers" around those you need:

https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/


On Wednesday, 27 May 2020 15:57:34 UTC+2, Daniel Roseman wrote:
>
> On Wednesday, 27 May 2020 13:21:24 UTC+1, ratnadeep ray wrote:
>>
>> Hi all, 
>>
>> Currently I am trying to print the type of a variable from the Django 
>> template html file as follows: 
>>
>> The type of feature list report for version 
>>> {%type(version)%} is
>>
>>
>> For the above, I am getting the following error: 
>>
>> Invalid block tag on line 9: 'type(version)'. Did you forget to register or 
>> load this tag?
>>
>>
>> So what's going wrong here? How can we use the python related api's (like 
>> type) from the html template files? I think inside the {%  %} we can 
>> use python related evaluations. Am I right? 
>>
>> Please throw some lights on this .
>>
>> Thanks. 
>>
>>
> No, you are wrong, and this is explicitly pointed out in the docs (
> https://docs.djangoproject.com/en/3.0/ref/templates/language/):
>
> > bear in mind that the Django template system is not simply Python 
> embedded into HTML. This is by design: the template system is meant to 
> express presentation, not program logic.
>
> --
> DR. 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/09e739dd-60c8-4360-9f9f-d3270c7901ca%40googlegroups.com.