curr = curr = get_object_or_None('Page', menu__slug=slug1, menu__parent__slug=slug2).prefetch_related('menu')
Need to use prefetch_related to get info from ForeignKey like an object and get None if it is not in table. Who knows, can I realize it by using get_object_or_None? It seems to work, but read, that it will not. Why so?
class Menu(models.Model):
name = models.CharField()
parent = models.ForeignKey('self', related_name='children')
slug = models.SlugField()
region = models.ForeignKey()
pos = models.IntegerField()
on_top = models.BooleanField()
nofollow = models.BooleanField()
class Page(models.Model):
title = models.CharField()
name = models.CharField()
menu = models.ForeignKey('Menu')
meta_key = models.TextField()
meta_desc = models.TextField()
body = models.TextField()
has_certificate = models.BooleanField()
get_object_or_None() is meant to be a shortcut to specifying a try except block, and it doesn't return a QuerySet, the class where prefetch_related() is from.
Also, if you're trying to get just one instance of your model you're not getting any performance enhancement by prefetching, in fact you'll make your query heavier on the db.
Related
I am trying to filter some data using this query,
get_members = PaymentDetails.objects.filter(participants_name=Participants.objects.filter(participants_name=Profile.objects.get(user=request.user)))
but I am getting this error The QuerySet value for an exact lookup must be limited to one result using slicing. My models looks like this
class Committee(models.Model):
committee_creator = models.ForeignKey(Profile, on_delete=models.CASCADE)
committee_name = models.CharField(max_length=100)
class Participants(models.Model):
participants_name = models.ForeignKey(Profile, on_delete=models.CASCADE)
participants_committee_name = models.ForeignKey(Committee, on_delete=models.CASCADE)
class PaymentDetails(models.Model):
participants_name = models.ForeignKey(Participants, on_delete=models.CASCADE)
participants_paid_status = models.BooleanField(default=False)
participants_amount_paid = models.IntegerField()
try this i will assume that you have OneToOne Relationship between User and Profile.
get_members = PaymentDetails.objects.filter(participants_name__participants_name_id = request.user.profile.pk)
I want to create a custom object list in the view and pass it to the template. In the template I want to loop over the list and display the information.
My models are
class CustomUser(AbstractUser):
def __str__(self):
return self.email
class Post(models.Model):
author = models.ForeignKey(CustomUser,on_delete=models.CASCADE,)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
post_url = models.URLField(max_length = 200, blank = True)
slug = models.SlugField(unique=True, blank=True)
class subscription(models.Model):
creator = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='creator',)
booster = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='booster')
sub_value = models.FloatField(blank = True)
sub_id = models.TextField(blank = True)
status = models.BooleanField(default=False)
dateSubscribed = models.DateTimeField(default=timezone.now)
dateSubscriptionEnded = models.DateTimeField(default=timezone.now)
paymentCount = models.FloatField(default= 0)
I want to filter objects from subscription model like below
subs = subscription.objects.filter(booster = request.user)
Then find creators in the above subs object list and for each creator get the name, numbers Posts, and number of Subscribers. Add this to custom list and pass it to the template to loop over and display the information in the template. Can someone help me how to create this custom list. Thanks!
Ok so here are the basics minus the subscribers because I don't see the relation clearly. This is how to parse the name and the number of posts. \
my_list = []
for sub in subs:
name = sub.creator.name
auth_id = sub.creator.id
posts = Post.objects.filter(author=auth_id)
num_of_posts = len(posts)
my_list.append({
'name':name,
'post_count': num_of_posts,
})
then you would pass mylist thru the template context.
It is a common mistake to name the related_name=… parameter [Django-doc] to the same value as the name of the field. The related_name parameter however is the name of the reverse relation Django will automatically add. So here it means a relation to access for example the related subscription objects of a given CustomUser.
Therefore it makes more sense to rename these, for example like:
class Subscription(models.Model):
creator = models.ForeignKey(
CustomUser,
default=None,
null=True,
on_delete=models.CASCADE,
related_name='created_subscriptions'
)
booster = models.ForeignKey(
CustomUser,
default=None,
null=True,
on_delete=models.CASCADE,
related_name='boosted_subscriptions'
)
sub_value = models.FloatField(blank=True)
sub_id = models.TextField(blank =True)
status = models.BooleanField(default=False)
dateSubscribed = models.DateTimeField(default=timezone.now)
dateSubscriptionEnded = models.DateTimeField(default=timezone.now)
paymentCount = models.FloatField(default=0)
Next we can make a query where:
from django.db.models import Count
CustomUser.objects.filter(
created_subscriptions__booster=request.user
).annotate(
number_of_posts=Count('post', distinct=True)
)
This is a QuerySet of CustomUsers where each CustomUser that arises from this QuerySet has an extra attribute .number_of_posts that contains the number of posts. You thus can iterate over the queryset directly in the template.
I'm working with django, during inserting data into tables the error is generates as given below...
Error:
int() argument must be a string, a bytes-like object or a number, not 'Tbl_rule_category', How can we solve such error?
view.py
dataToRuleCtgry = Tbl_rule_category(category=category, created_by="XYZ",created_date=datetime.date.today())
dataToRuleCtgry.save()
dataToRule = Tbl_rule(rule_name=rule_name, closure=closure,category_id=Tbl_rule_category.objects.latest('category_id'), created_by="XYZ",created_date=datetime.date.today(), updated_by="XYZ", updated_date=datetime.date.today(), rule_type=rule_type, fk_tbl_rule_tbl_rule_category_id=Tbl_rule_category.objects.latest('category_id'))
dataToRule.save()
models.py
class Tbl_rule_category(models.Model):
category_id = models.AutoField(primary_key=True)
category = models.CharField(max_length=50)
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
def __str__(self):
pass # return self.category, self.created_by
class Tbl_rule(models.Model):
rule_id = models.AutoField(primary_key=True)
rule_name = models.CharField(max_length=50)
closure = models.CharField(max_length=50)
category_id = models.IntegerField()
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
updated_by = models.CharField(max_length=50)
updated_date = models.DateField(auto_now=True)
rule_type = models.CharField(max_length=50)
fk_tbl_rule_tbl_rule_category_id = models.ForeignKey(Tbl_rule_category,on_delete=models.CASCADE, related_name='fk_tbl_rule_tbl_rule_category_id_r')
def __str__(self):
return self.rule_name, self.closure, self.created_by, self.updated_by, self.rule_type
The error is occurring because the following is trying to add an object into an integer field: category_id=Tbl_rule_category.objects.latest('category_id')
You could just add: category_id=dataToRuleCtgry.get('category_id') or category_id=dataToRuleCtgry.category_id which will solve the error.
You also don't need to add: created_date=datetime.date.today() because your model defines auto_now=true.
As mentioned you should also amend the def __str__(self): to return a string.
https://docs.djangoproject.com/en/2.0/ref/models/instances/#django.db.models.Model.str
Alternatively
You could just add the object link directly to your foreign key for the category model.fk_tbl_rule_tbl_rule_category_id=dataToRuleCtgry. You would no longer need the integer field category_id.
It would be better practice to use the model field name category_id instead of fk_tbl_rule_tbl_rule_category_id. This would mean deleting category_id and then rename fk_tbl_rule_tbl_rule_category_id to category_id.
In Django, the ORM takes care of the basic database details for you; which means in your code you really don't have to worry about individual row ids for maintaining foreign key relationships.
In fact, Django automatically assigns primary keys to all your objects so you should concentrate on fields that are relevant to your application.
You also don't have to worry about naming fields in the database, again Django will take care of that for you - you should create objects that have fields that are meaningful to users (that includes you as a programmer of the system) and not designed for databases.
Each Django model class represents a object in your system. So you should name the classes as you would name the objects. User and not tbl_user. The best practice is to use singular names. Django already knows how to create plural names, so if you create a model class User, django will automatically display Users wherever it makes sense. You can, of course, customize this behavior.
Here is how you should create your models (we will define __str__ later):
class RuleCategory(models.Model):
name = models.CharField(max_length=50)
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
class Rule(models.Model):
name = models.CharField(max_length=50)
closure = models.CharField(max_length=50)
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
updated_by = models.CharField(max_length=50)
updated_date = models.DateField(auto_now=True)
rule_type = models.CharField(max_length=50)
category = models.ForeignKey(RuleCategory,on_delete=models.CASCADE)
Django will automatically create any primary or foreign key fields, and any intermediary tables required to manage the relationship between the two models.
Now, to add some records:
new_category = RuleCategory(name='My Category', created_by='XYZ')
new_category.save()
# Another way to set values
new_rule = Rule()
new_rule.name = 'Sample Rule'
new_rule.closure = closure
new_rule.created_by = 'XYZ'
new_rule.updated_by = 'XYZ'
new_rule.rule_type = rule_type
new_rule.category = new_category
new_rule.save()
Note this line new_rule.category = new_category - this is how we link two objects. Django knows that the primary key should go in the table and will take care of that automatically.
The final item is customizing the models by creating your own __str__ method - this should return some meaningful string that is meant for humans.
class RuleCategory(models.Model):
name = models.CharField(max_length=50)
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
def __str__(self):
return '{}'.format(self.name)
class Rule(models.Model):
name = models.CharField(max_length=50)
closure = models.CharField(max_length=50)
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
updated_by = models.CharField(max_length=50)
updated_date = models.DateField(auto_now=True)
rule_type = models.CharField(max_length=50)
category = models.ForeignKey(RuleCategory,on_delete=models.CASCADE)
def __str__(self):
return '{} for category {}'.format(self.name, self.category)
If you notice something, I just put self.category in the __str__ for the Rule model. This is because we have already defined a __str__ for the RuleCategory model, which just returns the category name; so now when we print our Rule we created, we will get Sample Rule for category My Category as a result.
Here's what I'm trying to do :
The user creates an Event in my application. Here's the model :
class Event(models.Model):
name = models.CharField(max_length=40)
organizer = models.ForeignKey(UserProfile)
description = models.TextField(null=True)
place = models.TextField(null=True)
confirmed = models.BigIntegerField(null=True)
organizer_part = models.BooleanField(default=True)
slug = models.SlugField()
Right after that, it posts the different people invited to this event, and the different dates that the user chose. Here are the models :
class EventDate(models.Model):
"""Correspondances date-event"""
event = models.ForeignKey(Event)
date = models.BigIntegerField()
class EventPeople(models.Model):
"""Correspondances personne-event"""
event = models.ForeignKey(Event)
phone_number = models.PositiveIntegerField()
name = models.CharField(max_length=32)
answer = models.BooleanField()
participation = models.NullBooleanField()
I'd like to fill those three models in only one request. So far I have to make three requests. I can't see how I could possibly do it.
Any idea would be highly appreciated.
Resource that should work with your models is:
class EventResource(ModelResource):
event_dates = fields.ToManyField(EventDateResource, 'event_dates')
event_peoples = field.ToManyField(EventPeopleResource, 'event_peoples')
class Meta:
queryset = Event.objects.all()
Also you have to create simple EventDateResource and EventPeopleResource.
One one more change in yout models, you need to add related_names:
class EventDate(models.Model):
"""Correspondances date-event"""
event = models.ForeignKey(Event, related_name='event_dates')
date = models.BigIntegerField()
class EventPeople(models.Model):
"""Correspondances personne-event"""
event = models.ForeignKey(Event, related_name='event_peoples')
phone_number = models.PositiveIntegerField()
name = models.CharField(max_length=32)
answer = models.BooleanField()
participation = models.NullBooleanField()
I've added a MultivaluedField to my index (haystack), I need to search for a ManyToMany related field, but it doesn't work.
The engine is WHOOSH.
This how my index looks like:
class PostIndex(SearchIndex):
text = CharField(document=True, use_template=True)
author = CharField(model_attr='author')
body = CharField(model_attr='body')
pub_date = DateTimeField(model_attr='publish')
regions = MultiValueField()
def prepare_regions(self, obj):
return [region.name for region in obj.regions.all()]
And this how my model looks like:
class Post(models.Model):
title = models.CharField(_('title'), max_length=200)
author = models.ForeignKey(User, blank=True, null=True)
body = models.TextField(_('body'), )
allow_comments = models.BooleanField(_('allow comments'), default=True)
publish = models.DateTimeField(_('publish'), default=datetime.datetime.now)
categories = models.ManyToManyField(Category, blank=True)
tags = TagField()
objects = PublicManager()
regions = models.ManyToManyField(Region, blank=True)
If I use SearchQuerySet().filter(region__in=words_list) it works. The problem is that I don't know when the user is searching for a region or another field, so I have to use SearchQuerySet().filter(content__icontains=words_list). And in this way nothing is found.
Thanks
Thanks!!
Try :
class PostIndex(SearchIndex):
text = CharField(document=True, use_template=True)
author = CharField(model_attr='author')
body = CharField(model_attr='body')
pub_date = DateTimeField(model_attr='publish')
regions = CharField(model_attr='regions')
You only add region id to the index for Region.
Try
def prepare_regions(self, obj):
return [region.pk for region in obj.regions.all()]