Annotate querying, pk - django

How should I query when I use pk with annotate?
I need to redirect to user profile when a guest click in link.
Models
class Posty(models.Model):
title = models.CharField(max_length=250, blank=False, null=False, unique=True)
sub_title = models.SlugField(max_length=250, blank=False, null=False, unique=True)
content = models.TextField(max_length=250, blank=False, null=False)
image = models.ImageField(default="avatar.png",upload_to="images", validators=[FileExtensionValidator(['png','jpg','jpeg'])])
author = models.ForeignKey(Profil, on_delete=models.CASCADE)
updated = models.DateTimeField(auto_now=True)
published = models.DateTimeField(auto_now_add=True)
T_or_F = models.BooleanField(default=False)
likes = models.ManyToManyField(Profil, related_name='liked')
unlikes = models.ManyToManyField(Profil, related_name='unlikes')
created_tags = models.ForeignKey('Tags', blank=True, null=True, related_name='tagi', on_delete=models.CASCADE)
class CommentPost(models.Model):
user = models.ForeignKey(Profil, on_delete=models.CASCADE)
post = models.ForeignKey(Posty, on_delete=models.CASCADE, related_name="comments")
content1 = models.TextField(max_length=250, blank=False, null=False)
date_posted = models.DateTimeField(default=timezone.now)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.content1)
class Profil(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
age = models.PositiveIntegerField(blank=True, null=True)
country = models.CharField(max_length=50)
user = models.OneToOneField(Account, on_delete=models.CASCADE)
avatar = models.ImageField(default="avatar.png", upload_to="images",validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])])
slug = models.SlugField(blank=True)
gender = models.CharField(max_length=6, choices=GENDER)
friends = models.ManyToManyField(Account, blank=True, related_name="Friends")
social_facebook = models.CharField(max_length=250, null=True, blank=True)
social_instagram = models.CharField(max_length=250, null=True, blank=True)
social_twitter = models.CharField(max_length=250, null=True, blank=True)
social_youtube = models.CharField(max_length=250, null=True, blank=True)
social_linkedin = models.CharField(max_length=250, null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
Views
if tag == None:
my_tag = Posty.objects.annotate(
latest_comment = Subquery(CommentPost.objects.filter(post=OuterRef('id')).values('content1').order_by('-date_posted')[:1]),
my_author=Subquery(CommentPost.objects.filter(post=OuterRef('id')).values('user__user__username').order_by('-date_posted')[:1]),
)
I got a correct username, but I can't get a correct redirect:

Unfortunately, you need to annotate the CommentPost's id information as well with the queryset just like you added the username information. That will end up being a lot of subquery added to the original queryset. Rather I would suggest to use prefetch related to preload the CommentPost information with the original queryset (for reducing DB hits) and directly access that information from template. For example:
# view
my_tag = Posty.objects.prefetch_related('commentpost_set')
# template
{% for post in my_tag %}
<span> {{post.commentpost_set.last.content1}}<span>
<span> {{post.commentpost_set.last.user.username}}<span>
{% endfor %}
Also, last is a queryset function which returns the last object of a given queryset. I can access the CommentPost queryset from a Posty object by reverse querying.

Related

get the related records in a serializer - django

I am trying to obtain in a query the data of a client and the contacts he has registered I tried to do it in the following way but it did not work.
class ClientReadOnlySerializer(serializers.ModelSerializer):
clientcontacts = ClientContactSerializer(many=True, read_only=True)
class Meta:
model = Client
fields = "__all__"
Is there any way to make this relationship nested?
these are my models
clients model
# Relations
from apps.misc.models import City, TypeIdentity, TypeCLient, CIIU
from apps.clients.api.models.broker.index import Broker
from apps.authentication.models import User
class Client(models.Model):
id = models.CharField(max_length=255, unique=True,primary_key=True, editable=False)
type_client = models.ForeignKey(TypeCLient, on_delete=models.CASCADE, blank=True)
type_identity = models.ForeignKey(TypeIdentity, on_delete=models.CASCADE, blank=True)
document_number = models.CharField(max_length=255, blank=True, unique=True)
first_name = models.CharField(max_length=255, blank=True, null=True)
last_name = models.CharField(max_length=255, blank=True, null=True)
social_reason = models.CharField(max_length=255, blank=True, null=True)
city = models.ForeignKey(City, on_delete=models.CASCADE, blank=True)
address = models.CharField(max_length=255, blank=True)
email = models.CharField(max_length=255, blank=True, unique=True)
phone_number = models.CharField(max_length=255, blank=True, unique=True)
ciiu = models.ForeignKey(CIIU, on_delete=models.CASCADE, blank=True)
broker = models.ForeignKey(Broker, on_delete=models.CASCADE, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
income = models.SmallIntegerField(blank=True, default=0)
state = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(null=True, default=None)
client contacts model
# Relations
from apps.clients.api.models.index import Client
class ClientContact(models.Model):
id = models.CharField(max_length=255, primary_key=True, unique=True, editable=False)
client = models.ForeignKey(Client, on_delete=models.CASCADE)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
phone_number = models.CharField(max_length=255)
state = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(null=True, blank=True, default=None)
after some research I came up with a solution that doesn't seem very practical, what I did was to create a method in the serializer that queries the client's contacts as follows
class ClientReadOnlySerializer(serializers.ModelSerializer):
contacts = serializers.SerializerMethodField(method_name='get_contacts')
class Meta:
model = Client
fields = "__all__"
extra_fields = ['contacts']
def get_contacts(self, obj):
contacts = ClientContact.objects.filter(client=obj)
serializer = ClientContactSerializer(contacts, many=True)
return serializer.data
using the model and the serializer of the contact model I made a query which I added in an extra field of the customer serializer, if someone knows how to make this process more optimal please reply.

I receive an error while migrating my models to a database

I get such an error while migrating to a database:
return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: foreign key mismatch - "user_auth_customer"
referencing "user_auth_profile"
I have checked Foreign_Keys of my models and they look good.
I have no idea why I receive that error :(
Please, help me out here.
class Customer(AbstractUser):
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
profile = models.OneToOneField("Profile", related_name="user_profile",
on_delete=models.CASCADE, null=True)
first_name = models.CharField(max_length=50, null=True, blank=True)
last_name = models.CharField(max_length=50, null=True, blank=True)
username = models.CharField(max_length=30, null=True, blank=True)
phone = models.CharField(max_length=10, default='', null=True, blank=True)
email = models.EmailField(validators=[validators.EmailValidator()],
unique=True)
password = models.CharField(max_length=100, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
#staticmethod
def get_customer_by_email(email):
try:
return Customer.objects.get(email=email)
except:
return False
def isExists(self):
if Customer.objects.filter(email=self.email):
return True
return False
class Meta:
verbose_name = 'Customer'
verbose_name_plural = 'Customers'
class Profile(models.Model):
first_name = models.CharField(max_length=50, null=True, blank=True)
last_name = models.CharField(max_length=50, null=True, blank=True)
phone = models.CharField(max_length=10, default='', null=True, blank=True)
email = models.EmailField(primary_key=True, unique=True, validators=[validators.EmailValidator()])
password = models.CharField(max_length=100, null=True, blank=True)
# Add a photo field
owner = models.OneToOneField(Customer, related_name='profile_owner',
on_delete=models.SET_NULL, null=True)
username = models.CharField(max_length=30, null=True, blank=True,
validators=[UnicodeUsernameValidator()])
date_created = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = 'Profile'
verbose_name_plural = 'Profiles'
if you need any else details, I can provide you with those in the comments.
You can't have both ways OneToOneField. Choose one way.
If you delete Customer's profile field, then still you will have possibility to call relation with:
customer = Customer.objects.get(id=1)
customer.profile # that will call Customer's related Profile object
Assuming, that you will change related_name='profile_owner' to simpler related_name='profile'.
Read more about OneToOneRelationships.

How to display one models data in another model django admin panel

I have two models: 1) SchoolProfile & 2) Content
I want to show content data in schoolprofile, But data should be display as per user foreignkey.
User foreignkey common for both the models.
School Profile Model
class SchoolProfile(models.Model):
id=models.AutoField(primary_key=True)
user=models.ForeignKey(User,on_delete=models.CASCADE,unique=True)
school_name = models.CharField(max_length=255)
school_logo=models.FileField(upload_to='media/', blank=True)
incharge_name = models.CharField(max_length=255, blank=True)
email = models.EmailField(max_length=255, blank=True)
phone_num = models.CharField(max_length=255, blank=True)
num_of_alu = models.CharField(max_length=255, blank=True)
num_of_student = models.CharField(max_length=255, blank=True)
num_of_cal_student = models.CharField(max_length=255, blank=True)
def __str__(self):
return self.school_name
Content Model
class Content(models.Model):
id=models.AutoField(primary_key=True)
user=models.ForeignKey(User,on_delete=models.CASCADE)
content_type = models.CharField(max_length=255, blank=True, null=True)
show=models.ForeignKey(Show,on_delete=models.CASCADE, blank=True, null=True)
sponsor_link=models.CharField(max_length=255, blank=True, null=True)
status=models.BooleanField(default=False, blank=True, null=True)
added_on=models.DateTimeField(auto_now_add=True)
content_file=models.FileField(upload_to='media/', blank=True, null=True)
title = models.CharField(max_length=255)
subtitle = models.CharField(max_length=255, blank=True, null=True)
description = models.CharField(max_length=500, blank=True, null=True)
draft = models.BooleanField(default=False)
publish_now = models.CharField(max_length=255, blank=True, null=True)
schedule_release = models.DateField(null=True, blank=True)
expiration = models.DateField(null=True, blank=True)
tag = models.ManyToManyField(Tag, null=True, blank=True)
topic = models.ManyToManyField(Topic, null=True, blank=True)
category = models.ManyToManyField(Categorie, null=True, blank=True)
def __str__(self):
return self.title
I have used Inline but it's show below error:
<class 'colorcast_app.admin.SchoolProfileInline'>: (admin.E202) 'colorcast_app.SchoolProfile' has no ForeignKey to 'colorcast_app.SchoolProfile'.
My admin.py
class SchoolProfileInline(InlineActionsMixin, admin.TabularInline):
model = SchoolProfile
inline_actions = []
def has_add_permission(self, request, obj=None):
return False
class SchoolProfileAdmin(InlineActionsModelAdminMixin,
admin.ModelAdmin):
inlines = [SchoolProfileInline]
list_display = ('school_name',)
admin.site.register(SchoolProfile, SchoolProfileAdmin)
Using the StackedInline to link two models is straight forward and a much clean practice, so basically this is my solution below:
class ContentInlineAdmin(admin.StackedInline):
model = Content
#admin.register(SchoolProfile)
class SchoolProfileAdmin(admin.ModelAdmin):
list_display = ('school_name',)
inlines = [ContentInlineAdmin]

Django translate data from the DB {{ profession }}

Is it possible to translate DB entries? I have a dependent dropdown story that i need to translate. But i cant translate the dropdown fields, the fields come from other models and har hard coded. I can use HTML with JQ to achive this but i want to skip the manual labor to update the forms everytime new profession or professioncategories are added.
class Profession(models.Model):
name = models.CharField(max_length=30),
def __str__(self):
return self.name
class Professioncategory(models.Model):
profession = models.ForeignKey(Profession, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Skills(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
active = models.BooleanField(_('Active'), default=True)
profession = models.ForeignKey(Profession, on_delete=models.SET_NULL, null=True)
professioncategory = models.ForeignKey(Professioncategory, on_delete=models.SET_NULL, null=True)
posted_on = models.DateTimeField(_('Registrerad'), auto_now_add=True)
updated_on = models.DateTimeField(_('last updated'), auto_now=True)
years_of_exp = models.CharField(_('years of experiance'), max_length=20, choices=YEARS_OF_EXP, null=True, blank=True)

initial data in model field

I have a simple model:
class MediaLink(models.Model):
title = models.CharField(max_length=200)
subtitle = models.TextField(max_length=2000, unique=False, blank=True)
byline = models.CharField(max_length=200, unique=False, blank=True)
url = models.URLField(unique=False)
source = models.CharField(max_length=30, unique=False)
source_url = models.CharField(max_length=30, unique=False, blank=True, null=True, choices=SURL_CHOICES)
mediatype = models.CharField(max_length=30, choices=MEDIATYPE_CHOICES)
topic = models.CharField(max_length=30, choices=TOPIC_CHOICES)
sourceinfo = models.ForeignKey(SourceInfo, blank=True, null=True)
date_added = models.DateField(auto_now_add=True)
def __unicode__(self):
return u'%s' % self.title
class Meta:
abstract = True
class Admin:
pass
I'd like to set the "subtitle" field so that in each object, its initial data is "<h3></h3>". I'm using markdown and having the tags set initially saves me from having to create them in the admin for each record.
You could just set the default on the field:
subtitle = models.TextField(max_length=2000, unique=False, blank=True, default='<h3></h3>')
Or if you're using a ModelForm you can set it in the initial kwarg.