We have a webapp that has several product names in the django db. The db is queried for this table(?) and populates a drop down with these product names. I would like to hide these product names from the query/drop down without removing them from the DB.
Is there a way I can do this in sqlite?
I've inherited the project from a team member who has since left and am 2 days into my learning of Django so any assistance is welcome!
Sure, you have to use the Queryset.filter method when you query them!
Example:
items = Item.objects.filter(attribute = value)
This will only select items that have value for their attribute.
If you wan to do it the other way around, you can use Queryset.exclude
items = Item.objects.exclude(attribute = value)
This will only select items whose attribute is not equal to value.
Have a look at the documentation for more fun with the django ORM!
class Meta:
model = ChangeRequest
products = [(product.name, product.name) for product in Product.objects.all()]
products = [('', '--------')] + products
widgets = {
'product': forms.Select(choices=products),
Here's a snippet of my code,
it returns
Product1
Product2
Product3
Product4
I'm trying to use the exclude line you provided above and with the documentation but and not having much luck. How would I get it to return only Product2 and Product4?
I apologize if this is totally incorrect as it's my first time asking a question here.
Related
How can I filter over multiple many to many fields.
for example I've:
class Category(models.Model):
products = models.ManyToManyField(Product)
...
class Product(models.Model):
shippers = models.ManyToManyField(Shipper)
manufacturer = models.ForeignKey(Manufacturer)
...
With
products = Product.objects.filter(category=category)
I will get query with list of products in category.
How to get list of all possible shippers for all products in the category? The second question is how to get all instances of manufacturers from this query.
Now extracting of manufacturers looks like
manufacturer_ids = products.values_list('manufacturer').distinct()
manufacturers = Manufacturer.objects.filter(id__in=manufacturer_ids)
But i believe that should be better way
Also I don't have any idea how to get list of all possible shippers from this query.
To get all shippers of all products in a given Category:
shippers = Shipper.objects.filter(product__category=category)
It's possible that this will return duplicate values, so you can call .distinct() on it.
To get the manufacturers more neatly, you can do:
manufacturers = Manufacturer.objects.filter(products__in=products)
On the other hand, it seems more sensible to me to put the category field as a ForeignKey field on the Product model, rather than the other way round.
Hello folks Im new to Django(I have just the finished the tutorial) but I think i understand the basic concepts of it .Im writing here because Im trying to do something "difficult" for my current experience with django and searching the internet didnt give me a solution .What im trying to do is to create a dynamic model based on the number of entries of another model .To be more exact lets say i got the following model :
class criteria(models.Model):
criteria_text = models.CharField(max_length=200)
monotonicity = models.CharField(max_length=1,choices=(('+','ASCEDING'),('-','DESCENDING')),default='+',verbose_name='Monotonicity')
worst = models.IntegerField(default=0)
best = models.IntegerField(default=0)
What i want to do is create all the criteria models instances i want through the django admin panel and then query for all the creteria_text instances in the database and make a model with an attribute for every criteria_text instance.
So lets say I add the following criteria to the database(these are criteria_text attributes of criteria objects: Color,Weight,Price .
I want to end up with a model like this :
class Alternative(models.Model):
Color = models.IntegerField(default=0)
Weight = models.IntegerField(default=0)
Price = models.IntegerField(default=0)
The thing is that in my application this one has to happen a lot of times so i cannot make model each time someone adds an Alternative based on different criteria .
After searching i found that i can define dynamic models using the following format :
attrs = {
'name': models.CharField(max_length=32),
'__module__': 'myapp.models'
}
Animal = type("Animal", (models.Model,), attrs)
So the question is how can I define "attrs" based on a query that gets all the criteria in the database ?Can i define a relationship of this dynamic model with another model ? Also the models already created should be updated if a user adds more criteria .
Is something like this possible ?
If so please show me the path .
I don't think defining dynamic models is a good solution here (or anywhere, really). Rather, you need a relationship that can have as many items as there are criteria instances.
It might be something like this:
class Alternative(models.Model):
name = models.CharField(...)
choices = models.ManyToManyField("Criteria", through="AlternativeChoice")
class AlternativeChoice(models.Model):
alternative = models.ForeignKey('Alternative')
criteria = models.ForeignKey('Criteria')
value = models.IntegerField(default=0)
The real logic will belong in the form, where you will need to create options for each criteria entry, and validate the AlternativeChoice dependent on the related criteria.
My question is simple: in a Django app, I have a table Users and a table StatusUpdates. In the StatusUpdates table, I have a column user which is a foreign key pointing back to Users. How can I do a search expressing something like:
users.filter(latest_status_update.text__contains='Hello')
Edit:
Please excuse my lack of clarity. The query that I would like to make is something like "Give me all the users whose latest status update contains the text 'hello'". In Django code, I would do the following (which is really inefficient and ugly):
hello_users = []
for user in User.objects.all():
latest_status_update = StatusUpdate.objects.filter(user=user).order_by('-creation_date')[0]
if latest_status_update.text.contains('Hello'):
hello_users.append(user)
return hello_users
Edit 2:
I've already found the solution but since I was asked, here are the important parts of my models:
class User(models.Model):
...
class StatusUpdate(models.Model):
user = models.ForeignKey(User)
text = models.CharField(max_length=140)
creation_date = models.DateTimeField(auto_now_add=True, editable=False)
....
Okay, I think I got it:
from django.db.models import Max, F
User.objects\
.annotate(latest_status_update_id=Max('statusupdate__id'))\
.filter(
statusupdate__id=F('latest_status_update_id'),
statusupdate__text__icontains='hello'
)
For more info, see this section of the Django documentation.
Please note: I ended up changing my strategy a bit and settling for the strategy where the highest ID means the latest update. This is the case because I realized that a User could post two updates the same time and that would break my query.
latest_status_updates = filter(lambda x: x.text.contains('hello'),
[
user.statusupdates_set.order_by('-creation_date').first()
for user in User.objects.all()
]
)
users = list(set([status_update.user for status_update in latest_status_updates]))
EDIT:
Now I first get all LATEST status updates of each user into a list which is then filtered by the text field found in StatusUpdate class. In the second line, I extract users out of the filtered status updates and then produce a unique list of users.
I hope this helps!
Not sure I understand, are you trying to do something like
(StatusUpdates
.objects
.select_related("user")
.filter(text__contains = "hello")
.order_by("-updated")
.first())
This will return the StatusUpdate that was modified last (if you have a field called updated that stores the time of the last modification) which contains "Hello" in the text field. If none of the StatusUpdates contains that string, it will return None.
Then you can do:
latest = (StatusUpdates
.objects
.select_related("user")
.filter(text__contains = "hello")
.order_by("-updated")
.first())
#then if you needed the user too
if latest is not None:
user = latest.user #which does not call the DB again since you selected related`
If this isn't what you needed, please provide more details (models) and clarify your need
I have two models:
Base_Activity:
topics = models.ManyToManyField(Topic)
... some others
User_Activity:
user = models.ForeignKey(settings.AUTH_USER_MODEL)
activity = models.ForeignKey(Base_Activity)
is_archived = models.BooleanField(default=False)
Now I want to query Base_activity to select all rows with topic X and exclude any rows that have a matching row in User_Activity for user=*current_user* and is_archived=True.
I have read the Django docs on how to follow relationships backward, since I query Base_Activity, but need information from User_Activity which has a ForeignKey to the former. However, even testing this method in the Django console doesn't work:
a = Base_Activity.objects.filter(topics__slug = topic)
a.user_activity_set.all()
AttributeError: 'InheritanceQuerySet' object has no attribute 'user_activity_set'
Question: What is the best way to do my query? If this is indeed by following the ForeignKey backwards, then what am I doing wrong?
a = Base_Activity.objects.filter(topics__slug = topic)
This returns a QuerySet instance, not a model instance. You should iterate through it or just get one from the list:
activities = Base_Activity.objects.filter(topics__slug=topic)
activities[0].user_activity_set.all()
In your case you can do entire work in one query:
activities = Base_Activity.objects.filter(topics__slug=topic).exclude(user_activity__user=user, user_activity__is_archived=True)
I'm not sure this will solve your problem, but anyway please don't use underscores in your class names in Python.
I have a third party Django App (Satchmo) which has a model called Product which I make extensive use of in my Django site.
I want to add the ability to search for products via color. So I have created a new model called ProductColor. This model looks roughly like this...
class ProductColor(models.Model):
products = models.ManyToManyField(Product)
r = models.IntegerField()
g = models.IntegerField()
b = models.IntegerField()
name = models.CharField(max_length=32)
When a store product's data is loaded into the site, the product's color data is used to create a ProductColor object which will point to that Product object.The plan is to allow a user to search for a product by searching a color range.
I can't seem to figure out how to put this query into a QuerySet. I can make this...
# If the color ranges look something like this...
r_range, g_range, b_range = ((3,130),(0,255),(0,255))
# Then my query looks like
colors_in_range = ProductColor.objects.select_related('products')
if r_range:
colors_in_range = colors_in_range.filter(
Q(r__gte=r_range[0])
| Q(r__lte=r_range[1])
)
if g_range:
colors_in_range = colors_in_range.filter(
Q(g__gte=g_range[0])
| Q(g__lte=g_range[1])
)
if b_range:
colors_in_range = colors_in_range.filter(
Q(b__gte=b_range[0])
| Q(b__lte=b_range[1])
)
So I end up with a QuerySet which contains all of the ProductColor objects in that color range. I could then build a list of Products by accessing the products ManyToMany attribute of each ProductColor attribute.
What I really need is a valid QuerySet of Products. This is because there is going to be other logic which is performed on these results and it needs to operate on a QuerySet object.
So my question is how can I build the QuerySet that I really want? And failing that, is there an efficient way to re-build the QuerySet (preferably without hitting the database again)?
If you want to get a Product queryset you have to filter the Product objects and filter via the reverse relation for product color:
products = Product.objects.filter(productcolor_set__r__gte=x).distinct()
You can use the range field lookup:
You can use range anywhere you can use
BETWEEN in SQL -- for dates, numbers
and even characters.
your query:
r_range, g_range, b_range = ((3,130),(0,255),(0,255))
products = Product.objects.filter(productcolor_set__r__range=r_range,
productcolor_set__g__range=g_range,
productcolor_set__b__range=b_range).distinct()