I am trying to do a queryset filter using Django. I have Coupon objects with a code, which is a CharField. I want to find all Coupon objects with a matching code.
My model:
class Coupon(models.Model):
code = models.CharField(max_length=50)
... other fields
My view:
# This method returns the queryset
Coupon.objects.filter(code = "abc123")
# This part of the code is not working the way I want to
couponCode = str(request.POST.get("code"))
Coupon.objects.filter(code = couponCode)
I have ensured that the POST variable is "abc123" but I am still getting an empty queryset in the second query.
Just use
couponCode = request.POST['code']
instead of
couponCode = str(request.POST.get("code"))
Remove the str() part. Leave it only as:
couponCode = request.POST.get("code"),
then you could do:
Coupon.objects.filter(code=couponCode)
Hope this helps.
Related
I have a view in django that looks as follows:
class ExploreListingView(generics.ListAPIView):
serializer_class = ListingSerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
return Listing.objects.exclude(user=self.request.user, claimed=True)
The result I expect is to filter out any listings that are assigned with the current user and are claimed, however the filter doesn't work, but when I remove either parameter it works just fine. How do I exclude it so I can use more than one parameter.
It turns out all I had to do was chain the exclude methods, Listing.objects.exclude(user=self.request.user).exclude(claimed=True)
Listing.objects.filter(user=self.request.user, claimed=True)
You select entries that field user is equal self.request.user and claimed is True
and you can use :
Listing.objects.filter(user=self.request.user).exclude(claimed=True)
both ways is worked but the first is clearly code.
By "AND(&)" operator:
from django.db.models import Q
Listing.objects.filter(Q(user=self.request.user) & Q(claimed=True))
I have the following documents:
class Note(EmbeddedDocument):
value = mongo_db.StringField(max_length=200, required=True)
id = mongo_db.UUIDField(required=True, primary_key=True)
class Post(Document,):
notes = mongo_db.ListField(mongo_db.EmbeddedDocumentField(Note))
How to write a statement that update the value field for a Note object inside the list of a Post object. in other words how to write something that do the following:
update(post_id, note_id, new_valye)
In similar way, how I can delete an instance of the embedded documents Note:
delete(post_id, note_id)
First I edited My Post Document to get the benefits of EmbeddedDocumentListField:
class Note(EmbeddedDocument):
value = mongo_db.StringField(max_length=200, required=True)
id = mongo_db.UUIDField(required=True, primary_key=True)
class Post(Document,):
notes = mongo_db.EmbeddedDocumentListField(Note, required=False)
Then used for updating:
Post.objects(
id=post_id,
notes__id=note_id
).update(
set__notes__S__value=my_value
)
And for delete:
Post.objects(id=post_id).update_one(
pull__notes__id=note_id
)
But I think, there is a problems with this approach, first update now is hard to write if you are updating many fields.
You've got 2 ways of doing this, let's assume you want to update the second item of the list (i.e at index=1):
1) Get your document instance and use .save()
post = Post.objects().first()
post.notes[1].value = 'new_value'
post.save()
2) If all you need is updating a field of a document, and you know its position in the array, then you can use:
Post.objects.update(set__notes__1__value='new_value')
I have 3 models: User, Choice, Card. Each user will look at the same set of 10 cards and decides each one is important or not.
Here are how I define the classes and their relationship
In models.py:
class Choice(models.Model):
user = models.ForeignKey(User)
card = models.ManyToManyField(Card)
is_important = models.NullBooleanField()
class Card(models.Model):
card_number = models.IntegerField(primary_key=True)
content = models.TextField(null=False)
In views.py
(I try to save the choice for the card from the user. )
def listings(request):
user = request.user
choice = Choice.objects.create(user=user, is_important = True)
choice.card= Card.objects.get(1)
However, I got this error
'Card' object is not iterable
Could you please show me where the error is?
Many thanks!
You can add object against many to many field like this
card = Card.objects.create(card_number=any_number, content='abc')
choice.card.add(card)
First, it looks like you forgot pk= in your first .get() argument: Card.objects.get(pk=1)
Second, Choice.cards is a ManyToManyField that expects a list of items and not one in particular. You should set it through:
choice.card.set(Card.objects.filter(pk=1))
Please note that direct assignment with = will be deprecated from Django 1.10 and deleted in Django 2.0
.filter() will return a QuerySet (which is iterable). I think you wanted a ForeignKey instead of a M2M field, in which case your code would work (with the additional pk=).
In your function:
def listings(request):
user = request.user
choice = Choice.objects.create(user=user, is_important = True)
choice.card= Card.objects.get(1)
The following line is trying to fetch the Card object. However, we need to specify which card to be fetched.
If using an id, query it as:
choice.card= Card.objects.get(pk=1)
or else using list of ids:
choice.card = Card.objects.filter(pk__in=[12,22])
If using card_number field:
choice.card= Card.objects.get(card_number=1)
or else using list of card_numbers:
choice.card = Card.objects.filter(card_number__in=[12,22])
I asked a similar question today (Django: exclude User list from all Users ), the sollution was to write a symmetrical query. Since I changed my models with a many-to-many relation, this solution isn't valid anymore.
How can I exclude a list of users from user instances? With this method:
class Shift(models.Model):
shift_location = models.CharField(max_length=200)
users = models.ManyToManyField(User)
def get_shift_users(self):
return self.users.all()
def get_other_users(self):
return User.objects.all().exclude(self.users.all())
I get the error: AttributeError: 'User' object has no attribute 'split'
You need to use the in operator:
User.objects.exclude(id__in=self.users.all())
By using an unevaluated queryset (self.users.all()), it is transformed in a subquery, so the result will be fetched in a single query.
Maybe something like this:
User.objects.all().exclude(id__in=[u.id for u in self.users.all()])
I have a list a on the code, and i want to eliminate duplicated entries.
I saw a very clean method here: http://love-python.blogspot.pt/2008/09/remove-duplicate-items-from-list-using.html
i am using mysql
But when i acesss the page i get this error: 'list' object has no attribute 'all' i can't figure where this is coming from!
forms.py:
from testApp.models import Ficha_medico
from django.forms import ModelForm
from django import forms
class MenuForm(ModelForm):
a = Ficha_medico.objects.values_list('zona', flat=True)
a = list (set(a))
zona = forms.ModelChoiceField(queryset=a)
class Meta:
model = Ficha_medico
Any help appreciated
The error message tells you where it is coming from.
A list is not a queryset. You can't pass it as the queryset parameter of a field.
To eliminate duplicates in a queryset, use .distinct().
.values_list() returns a list object, not a queryset.
Apparently, something like this would work if you're using PostgreSQL:
a = Ficha_medico.objects.distinct('zona')
For others, I suspect there's a better way, but this would work:
class MenuForm(ModelForm):
items = Ficha_medico.objects.values_list(('id', 'zona'), flat=True)
# get a single 'id' per 'zona'
# --> since we don't know how many there are cycle through all
# --> note: this will overwrite existing values, but doesn't seem to matter.
uniques = {z: i for i, z in items}
# re-query to retrieve only the necessary number of unique zona values
qs = Ficha_medico.objects.filter(id__in=uniques.values())
zona = forms.ModelChoiceField(queryset=qs)
class Meta:
model = Ficha_medico