How to index just those models\rows, where some_field=some_value? - django

I use django-oscar + Solr + haystack.
*===============================================================================================================*
| id | partner_sku|price_currency|price_excl_tax|num_in_stock|date_created|date_updated|partner_id|product_id|
|"10451"|"S0010436" | "USD" | 74.00 | 20 |'some_date' |'some_date' | 1 | 5992 |
|"10452"|"S0010436" | "USD" | 80.00 | 0 |'some_date' |'some_date' | 2 | 5992 |
*===============================================================================================================*
I want to index just those rows where partner_id=2. index_queryset below does not do what I need, because other partners also indexed.
class ProductIndexes(CelerySearchIndex, indexes.Indexable):
text = indexes.EdgeNgramField(
document=True, use_template=True,
template_name='search/indexes/cpu/item_text.txt')
upc = indexes.CharField(model_attr="upc", null=True)
title = indexes.CharField(model_attr='title', null=True)
# Fields for faceting
product_class = indexes.CharField(null=True, faceted=True)
category = indexes.MultiValueField(null=True, faceted=True)
partner = indexes.MultiValueField(null=True, faceted=True)
price = indexes.FloatField(null=True, faceted=True)
vendor = indexes.CharField(null=True, faceted=True)
rating = indexes.IntegerField(null=True, faceted=True)
num_in_stock = indexes.BooleanField(null=True, faceted=True)
# Spelling suggestions
suggestions = indexes.FacetCharField()
date_created = indexes.DateTimeField(model_attr='date_created')
date_updated = indexes.DateTimeField(model_attr='date_updated')
def get_model(self):
return get_model('catalogue', 'Product')
def index_queryset(self, using=None):
return self.get_model().objects.filter(stockrecords__partner_id=2).order_by('-num_in_stock')
python manage.py rebuild_index is executed
How to implement indexing which I need?

Assuming this is the same issue: django oscar github issue 2169
As you're trying to filter on the num_in_stock which is a BooleanField????
i'd recommend changing this to an IntegerField and adding a `prepare_num_in_stock function like so:
def prepare_num_in_stock(self, obj)
# define get_local_stock as you please
return int(obj.get_local_stock())
Hope this helps.

Related

get attribut from other model with foreign key

I've a model with different fields.
I. E.
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
DB i.E.
id | first_name | Last_name | Instrument
1 | Stefan | Oslay | Bass
2 | Richard | Wagner | Klavier
Than I have a second model. I want to reference with foreign key the Musician. And then i want also a new custom field which contains also a attribut from Musician.
class MusikWerk(models.Model):
Interpret = models.ForeignKey(Musician, on_delete=models.CASCADE, null=FALSE, blank=False)
Title = models.CharField(max_length=50)
def instrument_wert(self)
return '%s '%(self.instrument)
instrument = instrument_wert(Musician)
DB i.E.
id | Interpretid | Title | Instrument
1 | 2 | TitelWagner | Klavier
But with my code i don't create the column Instrument in database and can't save the foreign field in them 😦

How to add list_display fields from a reverse relationship in django admin

I'm pretty new to django and the admin module. I'm looking for a way to add on a admin class
some fields that i query through a reverse relationship.
I can currently retrieve the interesting fields and put them in one column thanks to a specific function
using list_diplay, but i cannot manage to create a list_display field BY returned query object:
as example, now I get as column:
|Inventory_id| Mousqueton1 |
| 22 | foo1,foo2 |
and i would like to have this kind of output, to easily create filters:
|Inventory_id| Mousqueton1 | Mousqueton2 |
| 22 | foo1 | foo2 |
Here's my current models.py
class Kit(models.Model):
inventory_id = models.CharField(max_length=20,unique=True)
description = models.TextField(null=True)
creation_date = models.DateField(auto_now_add=True)
last_update = models.DateTimeField(auto_now=True)
class Mousquetons(models.Model):
inventory_id = models.CharField(max_length=20,unique=True)
serial = models.IntegerField(unique=False)
description = models.TextField(null=True)
creation_date = models.DateField(auto_now_add=True)
last_update = models.DateTimeField(auto_now=True)
kit = models.ForeignKey(Kit,on_delete=models.PROTECT,null=True)
and admin.py
#admin.register(Kit)
class KitAdmin(admin.ModelAdmin):
list_display= ['inventory_id','m']
def get_queryset(self, obj):
qs = super(KitAdmin, self).get_queryset(obj)
return qs.prefetch_related('mousquetons_set')
def m(self, obj):
return list(obj.mousquetons_set.all())
Maybe my data modeling is not the right way to perform this kind of operation, Any advice would be great.
Thanks !

Annotation of Similar Article Tags In Django Admin

I want to display similar tags count in the Django admin Tag section like this:
name | posts
-------------------------------
business | 3
Currently in my Tag table I have something this. This different posts that have similar tags to them.
name | post_id
-------------------------------
business | 1
business | 2
business | 3
My models
class Posts(models.Model):
title = models.CharField(max_length=500, verbose_name='Post Title')
class Tags(models.Model):
name = models.CharField(max_length=500)
date_created = models.DateField(auto_now_add=True, verbose_name='Date Created')
last_modified = models.DateField(auto_now=True, verbose_name='Last Modified')
post = models.ForeignKey(Posts, on_delete=models.CASCADE, verbose_name='Posts')
I have this in the admin.py
class TagAdmin(admin.ModelAdmin):
list_display = ('name', 'post_count', 'date_created', 'last_modified')
search_fields = ['name']
ordering = ['id']
readonly_fields=('date_created', 'last_modified')
def post_count(self, obj):
return obj.post_count
def get_queryset(self, request):
queryset = super().get_queryset(request)
queryset = queryset.annotate(post_count=Sum("post"))
return queryset
admin.site.register(Tags, TagAdmin)
This is how it looks in the admin panel
name | post_count
-------------------------------
business | 3
business | 3
business | 3
How do I achieve only displaying one instance of a tag name with all the posts that have that tag instead of the repetition above and instead the desired outcome below?
name | posts
-------------------------------
business | 3

Django Model Creating with Verbose Name

When creating a model object, can you use the verbose name to create? I have a model that has a dot in the name and I cannot have dot in a variable name.
file.xls
|---------|-----------------------|
| Start | ExonicFunc.UHNCLGGene |
|---------|-----------------------|
| 2488153 | nonsynonymous SNV |
| 3301721 | synonymous SNV |
|---------|-----------------------|
models.py
class Variant(models.Model):
start = models.CharField(max_length=10, null=True)
exonic_function = models.CharField(verbose_name="ExonicFunc.UHNCLGGene", max_length=20, null=True)
view.py
def upload(request):
# reads file.xls
raw_data = pandas.read_excel(request.FILES.get("file"))
for _, row in raw_data.iterrows():
variant = Variant.objects.create(**row)
verbose_name is just a label for your field in admin panel. You probably want to use db_column
exonic_function = models.CharField(db_column="ExonicFunc.UHNCLGGene", max_length=20, null=True)
and they assign value in your view as usual
variant.exonic_function = "bla"

How to know the owner who shared this file in this context in Django?

I have a table like this:
+----+----------+----------+----------------+----------------------------------+
| id | users_id | files_id | shared_user_id | shared_date |
+----+----------+----------+----------------+----------------------------------+
| 3 | 1 | 1 | 2 | 2013-01-31 14:27:06.523908+00:00 |
| 2 | 1 | 1 | 2 | 2013-01-31 14:25:37.760192+00:00 |
| 4 | 1 | 3 | 2 | 2013-01-31 14:46:01.089560+00:00 |
| 5 | 1 | 1 | 3 | 2013-01-31 14:50:54.917337+00:00 |
Now I want to know the owner of each files who shared the file. For file 1, users_id is 1. I want to get the name of users_id 1 from the default Django auth_user table. I want to get the usernames for each file. How can I do that?
#models.py
from django.db import models
from django.contrib.auth.models import User
class File(models.Model):
users = models.ForeignKey(User)
file_name = models.CharField(max_length=100)
type = models.CharField(max_length=10)
source = models.CharField(max_length=100)
start_date = models.TextField()
end_date = models.TextField()
duration = models.TextField()
size_overview = models.IntegerField()
size = models.TextField()
flag = models.TextField()
#delete_date = models.CharField(max_length=100, null=True, blank=True)
class Share(models.Model):
users = models.ForeignKey(User)
files = models.ForeignKey(File)
shared_user_id = models.IntegerField()
shared_date = models.TextField()
class Host(models.Model):
name = models.TextField()
full_path = models.TextField()
As I've said to you before, your model structure is a bit odd - in particular, Share.shared_user should be a ForeignKey, not an IntegerField. In this case, you could help things by making users a ManyToManyField from File to User, using Share as the through table:
class File(models.Model):
users = models.ManyToManyField(User, through='Share')
Now given a File instance you can simply do:
my_file.users.count()