NameError in Django simple search - python

I have a simple search in my Django project. I want to search through documents using their type and part of factory info in addition to search by name.
Here is my models.py:
class Docs(models.Model):
Date = models.DateField(default=date.today)
Name = models.CharField(max_length=50)
Type = models.ForeignKey(DocTypes)
Part = models.ForeignKey(Parts)
Link = models.FileField(upload_to='Docs/%Y/%m/%d')
class Parts(models.Model):
Name = models.CharField(max_length=50)
def __str__(self):
return str(self.Name)
class DocTypes(models.Model):
Type = models.CharField(max_length=50)
def __str__(self):
return str(self.Type)
My forms.py:
class DocsSearchForm(ModelForm):
class Meta:
model = Docs
fields = [ 'Name', 'Type', 'Part']
And this is part of my views.py, if no search was done then all documents are given
def showdocs(request):
if request.method == 'POST':
form = DocsSearchForm(request.POST)
documents = Docs.objects.filter(Name__contains=request.POST['Name']|
Type==request.POST['Type']|
Part==request.POST['Part'])
else:
form = DocsSearchForm()
documents = Docs.objects.all()
return render(
request,
'showdocs.html',
{'documents': documents, 'form':form}
So, the problem is the following: if I try to use a search then I have
NameError at /showdocs
name 'Type' is not defined.
POST values are:Part '1', Name 'Example', Type '1'.
If I delete
Type==request.POST['Type']|
Part==request.POST['Part']
then search by name works well. So I have a guess that problem is about searching by foreign key values, but have no ideas more. Will appreciate any help.

Try replacing the line with this
Docs.objects.filter(Name__contains=request.POST['Name'],
Type=request.POST['Type'],
Part=request.POST['Part']
)
It seems you have misunderstood the syntax. I don't know why you are trying to use | operator here.

That's not how Django filters work. You can't | them because they are not actually expressions, just keyword arguments. In this case, correct syntax would be:
Docs.objects.filter(
Name__contains=request.POST['Name'],
Type_Type=request.POST['Type'],
Part_Name=request.POST['Part'],
)`

Related

In Django, how do I get the corresponding key for a value passed in through the url?

Here is my models.py:
SHOW = (
(0,"Ballers"),
(1,"Silicon-Valley")
)
class Show(models.Model):
show = models.IntegerField(choices=SHOW, blank=True, null=True)
Here is from my urls.py:
urlpatterns = [
path('<str:show>/', views.ShowList.as_view(), name='show-list'),
]
Here is the function from views.py:
class ShowList(generic.ListView):
def get_queryset(self):
return Show.objects.filter(show=self.kwargs['show'])
I want to be able to have the url look like this: https://www.mywebsite.com/ballers, but when I try to run it, I get this error: Field 'show' expected a number but got 'ballers'. I know I can fix this by calling the url https://www.mywebsite.com/0, but I don't want the url to look like that.
In Django it takes first argument as the value to pass into db (field), so basically with:
return Show.objects.filter(show=self.kwargs['show'])
it tries to look directly with passing value. DB-wise it knows ONLY integers for that matter. So instead of looking directly, try to make small change:
class ShowList(generic.ListView):
def get_queryset(self):
show_string = self.kwargs['show']
show_int = [show[0] for show in Show.SHOW if show[1].lower() == show_string.lower()][0]
return Show.objects.filter(show=show_int)
and also move choices inside the model:
class Show(models.Model):
SHOW = (
(0,"Ballers"),
(1,"Silicon-Valley")
)
show = models.IntegerField(choices=SHOW, blank=True, null=True)

How to query a specific field in a model that has the same name as another field of another model

I'm trying to render the device that has the same name as the Gateway in the query so I created three models (The plant model has nothing to do with this issue so skip it ) as you can see in the models.py :
from django.db import models
infos_type= (
('ONGRID','ONGRID'),
('PV','PV'),
('HYBRID','HYBRID'),
)
infos_status= (
('etude','Etude'),
('online','Online'),
('Other','Other'),
)
infos_Device= (
('Rs485','Rs485'),
('lora','lora'),
('Other','Other'),
)
class new_Plant(models.Model):
name=models.CharField(max_length=20)
adress=models.CharField(max_length=50)
type=models.CharField(max_length=20,choices=infos_type)
location=models.CharField(max_length=50)
list_gateway=models.CharField(max_length=50)
status=models.CharField(max_length=50,choices=infos_status)
def __str__(self):
return self.name
#class Meta:
#db_table="website"
class new_Gateway(models.Model):
gatewayname=models.CharField(max_length=20)
slavename=models.CharField(max_length=20)
list_devices=models.CharField(max_length=20)
def __str__(self):
return self.gatewayname
class new_Device(models.Model):
Gateway_Name=models.CharField(max_length=20)
DeviceName=models.CharField(max_length=20)
slavename=models.CharField(max_length=20)
adress=models.CharField(max_length=20)
baud_rate=models.CharField(max_length=20)
connection_type=models.CharField(max_length=20,choices=infos_Device)
def __str__(self):
return self.DeviceName
# Create your models here.
Now as I said I want to render in a specific page , the device that Has "Gateway_Name" field same as the Gateway "gatewayname" field.
in my views.py this is what I tried but it doesn't work :
def gatewaysdevice(request,id):
gateway=new_Gateway.objects.get(id=id)
result=new_Device.objects.filter(Gateway_Name__contains=new_Gateway(gatewayname))
return render(request, 'website/gatewaysdevice.html',{'result':result})
You can try this query in your code:
result=new_Device.objects.filter(Gateway_Name__contains=gateway.gatewayname)
#If you encounter any type(object) error then use str(gateway.gatewayname).
Note : You can go with '__icontains' in above query which ignores lower and uppercase entries in Gateway_Name field for better approach.

get() returned more than one-- Django Restframework

I have a Django model which needs to have more than 1 images and more than 1 files (numbers may vary as per requirement), for which I adjusted my Admin Panel accordingly like this
models.py
class MasterIndividualMembers(models.Model):
individualmemberId = models.CharField(primary_key=True, max_length=100, default=1)
...
...
def __str__(self):
return self.firstname + " " + self.lastname
class IndividualMemberPhotos(models.Model):
individualmemberId = models.ForeignKey(MasterIndividualMembers, default=None,on_delete=models.CASCADE)
image = models.ImageField(upload_to="individualmemberphotos/")
class IndividualMemberCatalogue(models.Model):
individualmemberId = models.ForeignKey(MasterIndividualMembers, default=None,on_delete=models.CASCADE)
files = models.FileField(upload_to="individualmembercatalogue/")
admin.py
class IndividualMemberPhotosAdmin(admin.StackedInline):
model = IndividualMemberPhotos
class IndividualMemberCatalogueAdmin(admin.StackedInline):
model = IndividualMemberCatalogue
#admin.register(MasterIndividualMembers)
class MasterIndividualMembersAdmin(admin.ModelAdmin):
inlines = [IndividualMemberPhotosAdmin,IndividualMemberCatalogueAdmin]
class Meta:
model = MasterIndividualMembers
For the views I simply make a function to provide details of all the Images, Document and that User
views.py
#csrf_exempt
#api_view(['POST'])
#permission_classes([IsAuthenticated])
def get_individualmember(request):
if request.method == 'POST':
try:
individualmemberId = request.POST.get('individualmemberId')
result = {}
result['individualMemberDetails'] = json.loads(serializers.serialize('json', [MasterIndividualMembers.objects.get(individualmemberId=individualmemberId)]))
result['individualPhotoDetails'] = json.loads(serializers.serialize('json', IndividualMemberPhotos.objects.filter(individualmemberId__individualmemberId = individualmemberId)))
result['individualCatalogueDetails'] = json.loads(serializers.serialize('json', IndividualMemberCatalogue.objects.filter(individualmemberId__individualmemberId = individualmemberId)))
except Exception as e:
return HttpResponseServerError(e)
Problem: While fetching the details for any individual member, it throws an error get() returned more than one IndividualMemberPhotos -- it returned 2!, which is expected to have more than 1 objects.
How can I make the Restframework to provide me details of all image object together.
Instead of using get() which strictly returns a single element, use filter() which returns 0 or more elements.
As documented in https://docs.djangoproject.com/en/3.2/topics/db/queries/#retrieving-a-single-object-with-get
filter() will always give you a QuerySet, even if only a single object
matches the query - in this case, it will be a QuerySet containing a
single element.
If you know there is only one object that matches your query, you can
use the get() method on a Manager which returns the object directly:
The behavior you are experiencing is actually documented here https://docs.djangoproject.com/en/3.2/ref/models/querysets/#django.db.models.query.QuerySet.get
If get() finds more than one object, it raises a
Model.MultipleObjectsReturned exception:

django - how to sort objects alphabetically by first letter of name field

I have a model which has the fields word and definition. model of dictionary.
in db, i have for example these objects:
word definition
-------------------------
Banana Fruit
Apple also Fruit
Coffee drink
I want to make a query which gives me, sorting by the first letter of word, this:
Apple - also Fruit
Banana - Fruit
Coffee -drink
this is my model:
class Wiki(models.Model):
word = models.TextField()
definition = models.TextField()
I want to make it in views, not in template. how is this possible in django?
Given the model...
class Wiki(models.Model):
word = models.TextField()
definition = models.TextField()
...the code...
my_words = Wiki.objects.order_by('word')
...should return the records in the correct order.
However, you won't be able to create an index on the word field if the type is TextField, so sorting by word will take a long time if there are a lot of rows in your table.
I'd suggest changing it to...
class Wiki(models.Model):
word = models.CharField(max_length=255, unique=True)
definition = models.TextField()
...which will not only create an index on the word column, but also ensure you can't define the same word twice.
Since you tagged your question Django, I will answer how to do it using Django entities.
First, define your entity like:
class FruitWords(models.Model):
word = models.StringField()
definition = models.StringField()
def __str__(self):
return "%s - %s" % (self.word, self.definition)
To get the list:
for fruit in FruitWords.all_objects.order_by("word"):
print str(fruit)
If you are using class based ListView
class WikiListView(ListView):
model = Wiki
template_name = # Path to your html code. Example: 'appName/htmlFileName.html
def get_context_data(self, *args, **kwargs):
wiki_list = Wiki.objects.order_by('word')
context = super(WikiListView, self).get_context_data(*args, **kwargs)
context["wiki_list"] = wiki_list
return context
if you are using a simple view
def WikiView(request):
wiki_list = Wiki.objects.order_by('word')
return render(request, """HTML File""", {'wiki_list': wiki_list})
for example, I have an Article object that have a title field.
articles = list(sorted(articles, key=lambda obj:obj.title))
the issue you may run into is that you must require to return a QuerySet in class method occasions like get_queryset, the solution is stopping using a class based view and switch to a function view.

Finding objects without relationship in django

I am learning Django, and want to retrieve all objects that DON'T have a relationship to the current object I am looking at.
The idea is a simple Twitter copycat.
I am trying to figure out how to implement get_non_followers.
from django.db import models
RELATIONSHIP_FOLLOWING = 1
RELATIONSHIP_BLOCKED = 2
RELATIONSHIP_STATUSES = (
(RELATIONSHIP_FOLLOWING, 'Following'),
(RELATIONSHIP_BLOCKED, 'Blocked'),
)
class UserProfile(models.Model):
name = models.CharField(max_length=200)
website = models.CharField(max_length=200)
email = models.EmailField()
relationships = models.ManyToManyField('self', through='Relationship',
symmetrical=False,
related_name='related_to')
def __unicode__ (self):
return self.name
def add_relationship(self, person, status):
relationship, created = Relationship.objects.get_or_create(
from_person=self,
to_person=person,
status=status)
return relationship
def remove_relationship(self, person, status):
Relationship.objects.filter(
from_person=self,
to_person=person,
status=status).delete()
return
def get_relationships(self, status):
return self.relationships.filter(
to_people__status=status,
to_people__from_person=self)
def get_related_to(self, status):
return self.related_to.filter(
from_people__status=status,
from_people__to_person=self)
def get_following(self):
return self.get_relationships(RELATIONSHIP_FOLLOWING)
def get_followers(self):
return self.get_related_to(RELATIONSHIP_FOLLOWING)
def get_non_followers(self):
# How to do this?
return
class Relationship(models.Model):
from_person = models.ForeignKey(UserProfile, related_name='from_people')
to_person = models.ForeignKey(UserProfile, related_name='to_people')
status = models.IntegerField(choices=RELATIONSHIP_STATUSES)
This isn't particularly glamorous, but it gives correct results (just tested):
def get_non_followers(self):
UserProfile.objects.exclude(to_people=self,
to_people__status=RELATIONSHIP_FOLLOWING).exclude(id=self.id)
In short, use exclude() to filter out all UserProfiles following the current user, which will leave the user themselves (who probably shouldn't be included) and all users not following them.
i'v been searching for a method or some way to do that for like an hour, but i found nothing.
but there is a way to do that.
you can simply use a for loop to iterate through all objects and just remove all objects that they have a special attribute value.
there is a sample code here:
all_objects = className.objects.all()
for obj in all_objects:
if obj.some_attribute == "some_value":
all_objects.remove(obj)
Solution to the implementation of get_non_followers:
def get_non_following(self):
return UserProfile.objects.exclude(to_person__from_person=self, to_person__status=RELATIONSHIP_FOLLOWING).exclude(id=self.id)
This answer was posted as an edit to the question Finding objects without relationship in django by the OP Avi Meir under CC BY-SA 3.0.
current_userprofile = current_user.get_profile()
rest_of_users = Set(UserProfile.objects.filter(user != current_userprofile))
follow_relationships = current_userprofile.relationships.filter(from_person=current_user)
followers = Set();
for follow in follow_relationships:
followers.add(follow.to_person)
non_followeres = rest_of_users.difference(followers)
Here non_followers is the list of userprofiles you desire. current_user is the user whose non_followers you are trying to find.
I haven't tested this out, but it think it should do what you want.
def get_non_followers(self):
return self.related_to.exclude(
from_people__to_person=self)

Categories

Resources