Searching in several tables with django-haystack - django

I've got the Restaurant and Comment models shown below. The Comment model has a ForeignKey to Restaurant. How can I perform a search in some of the Restaurant fields and in the comment field of the Comment model which returns a list of Restaurant instances?
Thanks
class Restaurant(models.Model):
name = models.CharField(max_length=100)
country=models.ForeignKey(Country)
city=models.ForeignKey(City)
street=models.CharField(max_length=100)
street_number=models.PositiveSmallIntegerField()
postal_code=models.PositiveIntegerField(blank=True, null=True)
slug = models.SlugField(unique=True)
class Comment(models.Model):
user = models.ForeignKey(User)
restaurant = models.ForeignKey(Restaurant)
submit_date = models.DateTimeField(blank = True, null = False)
comment = models.TextField()

I think you should read the manual: http://django-haystack.readthedocs.org/en/latest/tutorial.html
look for multivalue:
class RestaurantIndex(indexes.SearchIndex):
comments = indexes.MultiValueField()
def prepare_comments(self, obj):
return [a for a in obj.comment_set.all()]

Related

fields in class Meta got invalid

models.py
class Product(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
price = models.DecimalField(decimal_places=5,max_digits= 1500)
summary = models.TextField()
featured = models.BooleanField()
def __str__(self):
return self.title
# return f'product title:{self.title}-product price:{self.price}'workok
class Meta:
ordering = ('-price',)
class Opinion(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(max_length=20)
body = models.TextField()
opinion_date = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='opinion_set')
def __str__(self):
return f'({self.name}) add opinion about ({self.product})'
forms.py:
from django.forms import ModelForm
from .models import Product #space after from keyword
class OpinionModelForm(ModelForm):
class Meta:
model = Product
fields = ['name','email','body','product']
invalid in code line :
fields = ['name','email','body','product'] #---- NOT WORK !!!
, but if i change above code to :
fields = "__all__" # ----it is WORKing ok without any problem !!
question : what is the error? I am not need all the fields in the Product model (like active boolean field), I need only 'name','email','body','product' fields .
According to the error and the code you provided the main problem is that you made a mistake in chosing model in serializer:
class OpinionModelForm(ModelForm):
class Meta:
model = Product
fields = ['name','email','body','product']
Serializer name is OpinionModelForm and listed fields belong to Opinion so I guess you actually wanted to serialize Opinion and no Product as you defined at this line:
model = Product
Simply change it to:
model = Opinion

Django REST framework, dealing with related fields on creating records

Preliminary note: this is a rather newbie question, though I have not found a sufficient answer on StackOverflow; many similar questions, but not this one. So I am asking a new question.
The problem: I'm having difficulty creating records where one field is a foreign key to an existing record, and I do not know what I'm doing wrong in my code.
In my app there are two models in question, a one-to-many relationship between Company and BalanceSheet:
models:
class Company(models.Model):
cik = models.IntegerField(default=0, unique=True)
symbol = models.CharField(max_length=4, unique=True)
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.symbol
class BalanceSheet(models.Model):
company = models.ForeignKey(Company,
null=True,
on_delete=models.CASCADE,
related_name='balance_sheets',)
date = models.DateField()
profit = models.BigIntegerField()
loss = models.BigIntegerField()
class Meta:
unique_together = (('company', 'date'),)
def __str__(self):
return '%s - %s' % (self.company, self.date)
serializers:
class BalanceSheetSerializer(serializers.ModelSerializer):
company = serializers.StringRelatedField()
class Meta:
model = BalanceSheet
fields = ('company','date','profit','loss')
class CompanySerializer(serializers.ModelSerializer):
class Meta:
model = Company
fields = ('cik', 'symbol', 'name')
Views:
class BalanceSheetCreate(generics.CreateAPIView):
model = BalanceSheet
queryset = BalanceSheet.objects.all()
serializer_class = BalanceSheetSerializer
urls include:
url(r'^(?P<symbol>[A-Z]{1,4})/create-balance-sheet/$', views.BalanceSheetCreate.as_view(),
name='create_balance_sheet'),
To this point, I have zero problem reading data. However, when trying to create records, I get errors I don't understand:
curl http://localhost:8000/financials/AAPL/create-balance-sheet/ -X POST -d "company=AAPL&date=1968-04-17&profit=1&loss=1"
IntegrityError at /financials/AAPL/create-balance-sheet/
null value in column "company_id" violates not-null constraint
Dropping the company data from that curl command results in the same error.
How do I get around this error? I thought I was telling the api what company I'm interested in, both explicitly in the url and in the post data.
Using python3.6, django 1.11, and djangorestframework 3.7.7
You get the IntegrityError because your code will try to create a new BalanceSheet without a company. That's because StringRelatedField is read-only (see docs) and therefore it's not parsed when BalanceSheetSerializer is used in write mode.
SlugRelatedField is what you need here:
class BalanceSheetSerializer(serializers.ModelSerializer):
company = serializers.SlugRelatedField(slug_field='symbol')
class Meta:
model = BalanceSheet
fields = ('company','date','profit','loss')
To answer my own question, here's what I wound up with. Thanks again go to dukebody.
models:
class Company(models.Model):
cik = models.IntegerField(default=0)
symbol = models.CharField(max_length=4)
name = models.CharField(max_length=255)
def __str__(self):
return self.symbol
class BalanceSheet(models.Model):
company = models.ForeignKey(Company,
null=True,
on_delete=models.CASCADE,
related_name='balance_sheets',)
date = models.DateField()
profit = models.BigIntegerField()
loss = models.BigIntegerField()
class Meta:
unique_together = (('company', 'date'),)
def __str__(self):
return '%s - %s' % (self.company, self.date)
serializers:
class CompanySerializer(serializers.ModelSerializer):
class Meta:
model = Company
fields = ('cik', 'symbol', 'name')
class BalanceSheetSerializer(serializers.ModelSerializer):
company = CompanySerializer(many=False)
class Meta:
model = BalanceSheet
fields = ('company', 'date', 'profit', 'loss')
def create(self, validated_data):
company_data = validated_data['company']
company, created = Company.objects.get_or_create(**company_data)
validated_data['company'] = company
sheet = BalanceSheet.objects.create(**validated_data)
return sheet
I also had to include the full company data within my curl statement as a nested dict.

django queryset filter foreignkey

I'm having problems trying to use the queryset filter with my models.
It is a control for posts in groups.
This is my code:
class Post(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
class Group(models.Model):
title = models.CharField(max_length=200)
url = models.URLField(unique=True)
class Control(models.Model):
published = models.DateField(auto_now=False, auto_now_add=False)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
I'm trying to get all posts from a group with the title "title":
queryset_list = Control.objects.filter(group__control="title")
My models might nit be right, I'm new to this.
Any help?
Maybe it typo error?
queryset_list = Control.objects.filter(group__title="title")
# ^^^^^^
posts_title = queryset_list.values('post__title')
First, you should add a ManyToManyField on Group (docs):
class Group(models.Model):
title = models.CharField(max_length=200)
url = models.URLField(unique=True)
posts = models.ManyToManyField('Post', through='Control')
The other two models remain the same, but now you can easily grab posts for a Group:
posts = Group.objects.get(title='some title').posts.all()

Django Many to Many Relationship backward querying

I have 2 models named 'Author' and 'Entry' as defined below.
class Author(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
msgtoauthor = models.TextField()
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateTimeField()
authors = models.ManyToManyField(Author)
I am trying to access 'Author.msgtoauthor' from 'Entry'.
I know, I can retrieve the relationship between Entry and Author by
e = Entry.objects.get(authors)
Is it possible to extract the author id?
I know in the backend, Django creates a table for Authors and Entries but I want to update 'msgtoauthors' from a method in 'Entry'.
Thanks In Advance.
Did you mean
for author in my_entry.authors.all():
author.msgtoauth = 'Here is new content'
author.save()
?
Entry.authors returns a RelatedManager and my_entry.authors.all() is a QuerySet, that returns the Author objects. See https://docs.djangoproject.com/en/1.3/ref/models/relations/ and https://docs.djangoproject.com/en/1.3/topics/db/models/#many-to-many-relationships.
(Updated.)
Try this:
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateTimeField()
authors = models.ManyToManyField(Author)
def msgtoat(self, message):
self.authors.update(msgtoauthor=message)
For example, to update an entry:
entry.msgtoat('Hello')
If all the authors get the same value you can do:
entry.authors.update(msgtoauthor='Hey there!')
https://github.com/Ry10p/django-Plugis/blob/master/courses/models.py
line 52
class name():
the_thing1 = models.CharField()
another = models.TextField()
class name2():
the_thing2 = models.ForignKey(the_thing1)
another2 = models.ForignKey(another)
-Cheers

django: how does manytomanyfield with through appear in admin?

As stated in the title how does manytomanyfield with through appear in the admin site?
class SchoolClass(models.Model):
id = models.AutoField(primary_key = True)
class_name = models.TextField()
level = models.IntegerField()
taught_by = models.ManyToManyField(User,related_name="teacher_teaching",through='TeachSubject')
attended_by = models.ManyToManyField(User,related_name='student_attending')
def __unicode__(self):
return self.class_name
class Meta:
db_table = 'classes'
class TeachSubject(models.Model):
teacher = models.ForeignKey(User)
class_id = models.ForeignKey(SchoolClass)
subject = models.ForeignKey(Subject)
In the admin site, for the model SchoolClass, I have a field for attending students, but not the teachers.
You should use InlineModelAdmin. Docs.
class TeachSubjectInline(admin.TabularInline):
model = TeachSubject
extra = 2 # how many rows to show
class SchoolClassAdmin(admin.ModelAdmin):
inlines = (TeachSubjectInline,)
admin.site.register(SchoolClass, SchoolClassAdmin)