I am really confusing about Django joins. I want to search a keyword in two tables with a single query. can anyone help me?
the app model structure like this
class Events(models.Model):
event_type = models.CharField(_("Event Type"), max_length=5, choices=event_type_choices)
webinar_title = models.CharField(_("Webinar Title"), max_length=50, blank=True, null=True)
event_name = models.CharField(_("Event Name"), max_length=50, blank=True, null=True)
banner_title = models.CharField(_("Banner Title"), max_length=50, blank=True, null=True)
added_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL)
status = models.BooleanField(_("Event Status"), default=True)
class Meta:
verbose_name = _('Event')
db_table = 'events'
app_label = 'events'
class WebinarSpeakers(models.Model):
event = models.ForeignKey(Events, on_delete=models.CASCADE, null=True)
speaker = models.CharField(_("Speaker Name"), max_length=100, null=True, blank=True)
job_title = models.CharField(_("Job Title"), max_length=255)
place_of_work = models.CharField(_("Place of Work"), max_length=100)
credentials = models.TextField(_("Credentials"), null=True, blank=True)
image = models.ImageField(_("Speaker Image"), upload_to=speaker_file_name, null=True, blank=True)
class Meta:
verbose_name = _('Event Webinar Speakers')
db_table = 'webinar_speakers'
app_label = 'events'
Now I want to search a keyword in webinar_title, evetn_name, banner_title, speaker, 'job_title` with a single query. how to do it in Django joins. I read the select_related document. it confusing me.
WebinarSpeakers.objects.filter(event__webinar_title="something", event__event_name="something", event__banner_title="somethng", speaker="something",job_title="something")
Related
The Loading time is too much for this particular model in admin panel.I know it is because I have too many values in Foreign Fields (field with 20k+ records each) which takes too much time to load on client side. Is there a way to optimise this? below is my code and screenshot of loadtime,
Loading Time
Models:
class Alert(BaseModelCompleteUserTimestamps):
type = models.ForeignKey(to=AlertType, on_delete=models.CASCADE, verbose_name="Type")
device = models.ForeignKey(Device, on_delete=models.CASCADE, related_name="alert_device")
device_event = models.ForeignKey("dm_detection.VIDSDetection",
on_delete=models.CASCADE, null=True, blank=True, related_name="device_event")
anpr_event = models.ForeignKey("dm_detection.VSDSDetection",
on_delete=models.CASCADE, null=True, blank=True, related_name="anpr_event")
ecb_event = models.ForeignKey("dm_detection.ECBDetection",
on_delete=models.CASCADE, null=True, blank=True, related_name="ecb_event")
hr_only = models.IntegerField(null=True, blank=True)
# acknowledged
is_acknowledged = models.BooleanField(default=False, verbose_name="Acknowledged")
acknowledged_at = models.DateTimeField(blank=True, null=True)
acknowledged_by = models.ForeignKey(to=User, on_delete=models.CASCADE, null=True, blank=True,
related_name="alert_acknowledged_by")
# resolved
is_resolved = models.BooleanField(default=False, verbose_name="Resolved")
resolved_at = models.DateTimeField(blank=True, null=True)
resolved_by = models.ForeignKey(to=User, on_delete=models.CASCADE, null=True, blank=True,
status = models.ForeignKey(to=TicketStatus, on_delete=models.DO_NOTHING, default=1)
Admin.py
#admin.register(Alert)
class AlertModelAdmin(BaseModelCompleteUserTimestampsAdmin):
form = AlertEditForm
fields = ('type',
'device',
'device_event',
'status', 'hr_only',
'is_acknowledged', 'acknowledged_at', 'acknowledged_by',
'is_resolved', 'resolved_at', 'resolved_by', 'anpr_event',
'created_at',
'updated_at', 'OD_vehicle_number'
)
Forms.py
class AlertEditForm(forms.ModelForm):
status = forms.ModelChoiceField(queryset=TicketStatus.objects.filter(is_for_alert=True))
device_event = forms.ModelChoiceField(queryset=VIDSDetection.objects.all())
anpr_event = forms.ModelChoiceField(queryset=VSDSDetection.objects.all())
acknowledged_by = forms.ModelChoiceField(queryset=User.objects.all())
resolved_by = forms.ModelChoiceField(queryset=User.objects.all())
class Meta:
model = Alert
fields = '__all__'
models:
class FullNameMixin(models.Model):
name_id = models.BigAutoField(primary_key = True, unique=False, default=None, blank=True)
first_name = models.CharField(max_length=255, default=None, null=True)
last_name = models.CharField(max_length=255, default=None, null=True)
class Meta:
abstract = True
class Meta:
db_table = 'fullname'
class User(FullNameMixin):
id = models.BigAutoField(primary_key = True)
username = models.CharField(max_length=255, unique=True)
email = models.CharField(max_length=255, unique=True)
token = models.CharField(max_length=255, unique=True, null=True, blank=True)
password = models.CharField(max_length=255)
role = models.IntegerField(default=1)
verified = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)
def __str__(self):
return self.username
class Meta:
db_table = 'cga_user'
class Profile(FullNameMixin):
id = models.BigAutoField(primary_key = True)
birthday = models.DateTimeField(null=True, blank=True)
country = models.CharField(max_length=255, null=True, blank=True)
state = models.CharField(max_length=255, null=True, blank=True)
postcode = models.CharField(max_length=255, null=True, blank=True)
phone = models.CharField(max_length=255, null=True, blank=True)
profession_headline = models.CharField(max_length=255, null=True, blank=True)
image = models.ImageField(upload_to=get_upload_path, null=True, blank=True)
profile_banner = models.ImageField(upload_to=get_upload_path_banner, null=True, blank=True)
cga_user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE, related_name="profile")
gender = models.CharField(
max_length=255, blank=True, default="", choices=USER_GENDER_CHOICES
)
created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)
class Meta:
db_table = 'profile'
When i am creating Profile from django admin panel getting below error.
e
filename = self.upload_to(instance, filename)
File "/Users/soubhagyapradhan/Desktop/upwork/africa/backend/api/model_utils/utils.py", line 7, in get_upload_path
instance.user,
File "/Users/soubhagyapradhan/Desktop/upwork/africa/backend/env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 421, in __get__
raise self.RelatedObjectDoesNotExist(
api.models.FullNameMixin.user.RelatedObjectDoesNotExist: Profile has no user.
[24/Jul/2021 13:49:51] "POST /admin/api/profile/add/ HTTP/1.1" 500 199997
please take a look how can i fix this.
Note: User model creation working but, profile not working
I checked in drf and django admin panel .
both place not working.
The problem here is that you are declaring a User model which is in fact just a model. That's not how it works.
The User is a special type of model and if you want to change it you have to extend the AbstractUser class.
Alternatively you can connect to it via one-to-one classes in the classic user-profiles approach.
But here you are creating a user model that (besides using the reserved word 'User') has none of the requirements necessary to be treated as a user who can be authenticated and that can instantiate sessions.
> Example of a simple user-profiles architecture
> Working with User objects - Django Docs (i particularly recommend this one)
I would recommend you to read-up on django user authentication.
I am a Django newbie. I cannot figure out how to create a form that properly displays my model, which has two ForeignKey fields and three ManytoManyFields. I am familiar with creating forms from more simple models, but I'm stuck on this one. So far, I've tried ModelForm and used ModelChoiceField for ForeignKey relationships, but that did not work. When viewing the form, the fields options did not render. I then tried inlineformset_factory but I could not find helpful examples. Any help is appreciated.
I am trying to create CreateView, UpdateView, and DeleteView options for the model.
models.py
class Animal(models.Model):
name = models.CharField(max_length=500, blank=False, null=False)
**atype = models.ForeignKey(Type, on_delete=models.SET_NULL, blank=False, null=True)**
**ageGroup = models.ForeignKey(AgeGroup, max_length=300, on_delete=models.SET_NULL, blank=False, null=True)**
ageYears = models.PositiveIntegerField(blank=False, null=False)
ageMonths = models.PositiveIntegerField(blank=True, null=True)
sex = models.CharField(max_length=100, choices=SEX, blank=False, null=False, default='NA')
city = models.CharField(max_length=200, blank=True, null=True)
state = models.CharField(max_length=200, blank=True, null=True)
country = models.CharField(max_length=250, blank=True, null=True)
**breedGroup = models.ManyToManyField(BreedGroup, blank=False)**
**breed = models.ManyToManyField(Breed, blank=False)**
tagLine = models.CharField(max_length=300, blank=False, null=False)
goodWithCats = models.BooleanField(blank=False, null=False, default='Not Enough Information')
goodWithDogs = models.BooleanField(null=False, blank=False, default='Not Enough Information')
goodWKids = models.BooleanField(null=False, blank=False, default='Not Enough Information')
profilePic = ResizedImageField(size=[300, 450], quality=100, upload_to='media/', default='', null=True, blank=True, keep_meta=False)
**contact = models.ForeignKey(ContactDetails, on_delete=models.SET_NULL, blank=False, null=True)**
forms.py
class AnimalDetailsForm(ModelForm):
ftype = ModelChoiceField(queryset=Type.objects.all()) #doesn't work
ageGroup = ModelChoiceField(queryset=AgeGroup.objects.all()) #doesn't work
#breed = what method to use?
#breedGroup = what method to use?
class Meta:
model = Animal
exclude = ['ftype', 'ageGroup', 'breed', 'breedGroup']
Also in the Meta of your form you are excluding the fields you are trying to get data for. It should say
class Meta:
model = Animal
fields = ['type', 'ageGroup', 'breed', 'breedGroup']
Docs consulted: https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/
https://docs.djangoproject.com/en/3.1/ref/models/fields/
**edit, removed comment about using type as a variable name.
When I run my Django project on production server, I have this error:
ProgrammingError at /admin/core/event/
column core_event.hometask does not exist
LINE 1: ..._event"."is_approved", "core_event"."event_type", "core_even...
What I should do to fix it? Now I haven't "hometask" field in my model:
class Event(models.Model):
name = models.CharField(max_length=100, null=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
description = models.TextField(max_length=1000, blank=True, null=True)
date_start = models.DateTimeField(null=True, blank=True)
date_finish = models.DateTimeField(null=True, blank=True)
image = models.ImageField(
upload_to="event_images/", default='event_images/default.png', blank=True, null=True)
is_approved = models.BooleanField(null=True)
TYPE_CHOICES = (
('Event', "Мероприятие"),
('Lesson', "Урок"),
)
event_type = models.CharField(choices=TYPE_CHOICES, max_length=200, default="Мероприятие")
topics = ArrayField(models.CharField(max_length=200), blank=True, null=True)
materials = ArrayField(models.URLField(), blank=True, null=True)
possible_users = models.ManyToManyField("core.User", blank=True, related_name='possible_users')
actual_users = models.ManyToManyField("core.User", blank=True, related_name='actual_users')
classes = models.ManyToManyField("core.Class", blank=True, related_name='classes')
From what you posted, looks like the field existed in the model before but not anymore. However, your admin.py still has reference to the old field of hometask.
So, go to admin.py, search for hometask, and remove it.
I am using Django 2.07. In my application after posting the first post, the second post it is not taking a post under the same username (I'm using Django all-auth). At Django admin, it shows me "this username already exits."
this is my profile model:
class Profile(models.Model):
PUBLIC = 'Public'
PRIVATE = 'Private'
INITIATIVE ='Initiative'
PRIVATE_STARTUP = 'Private and Startup'
INITIAL_KEYWORD = (
(PUBLIC, 'Public'),
(PRIVATE, 'Private'),
(INITIATIVE, 'Initiative'),
(PRIVATE_STARTUP, 'Private and Startup'),
)
Type_of_account = models. NullBooleanField('Personal account',
help_text="by default this is Business account")
user_photo = models.ImageField(upload_to='user_image', blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE, default=1)
occupation = models.CharField(max_length=400, null=False)
name = models.CharField(max_length=200, null=False, blank=False, default=None)
title = models.CharField(max_length=100, null=True, blank=True)
url = models.URLField(max_length=200, null=True, blank=True)
additional_url = models.URLField(max_length=200, null=True, blank=True )
Headquarter = models.CharField(max_length=1000, null=True, blank=True)
stock_market = models.CharField(max_length=200, null=True, blank=True)
established = models.DateField(auto_now=False, auto_now_add=False, default=None)
investors = RichTextField(null=True, blank=True)
about_details = RichTextField(null=False, blank=False, default=None)
Type_of_company = models.CharField(
max_length=20,
null=True,
blank=True,
choices=INITIAL_KEYWORD,
default=PRIVATE_STARTUP)
This is my main-model.
class MainModel(models.Model):
I_THINK = 'I think'
GOOD_PART = 'Good part'
BAD_PART ='Bad part'
PROTOTYPE = 'Prototype'
FEEDBACK = 'Feedback'
INFO = 'Info'
REVIEW = 'Review'
ASK = 'Ask'
FINACIAL_MARKET = 'Financial market'
INITIAL_KEYWORD_FOR_THOUGHTS = (
(I_THINK, 'I THINK'),
(FEEDBACK, 'FEEDBACK'),
(GOOD_PART, 'GOOD PART'),
(BAD_PART, 'BAD PART'),
(PROTOTYPE, 'PROTOTYPE'),
(INFO, 'INFO'),
(REVIEW, 'REVIEW'),
(ASK, 'ASK'),
(FINACIAL_MARKET, 'FINANCIAL MARKET')
)
user = models.OneToOneField(User, on_delete=models.CASCADE, default=None)
pub_time = models.DateTimeField('Publish time', auto_now=True)
topic = models.CharField(max_length=2000, null=True, blank=True)
##
micro_thought = models.CharField(max_length=200, null=True, blank=True)
Initial_keyword_for_thoughts = models.CharField(
max_length=300,
null=True,
blank=True,
choices=INITIAL_KEYWORD_FOR_THOUGHTS,
default=I_THINK
)
What kind of changes I have to make at main-models user field?
how I can solve this problem?
Thank you for your help.
You are using OneToOne field to relate user to Post. Using OnetoOne field a user can have atmost one post. That is the issue. Change it to ForeignKey relation.
user = models.ForeignKey(User, on_delete=models.CASCADE, default=None)