How to fetch custom column which does not exist in database table? - django

How can I implement followig SQL QUERY in django rest framework
`SELECT `id` , `name_hi` as hi , `name_en` as en , false as `checked` FROM `tab_name`
where checked does not exist in the database table i.e. it is not a column .
id | hi | en | checked
1 | xx | xx | 0
2 | hi2| en2| 0
3 | hi3| en3| 0
I am using Django Rest framework.
How can I rename these fields also include checked
So far I have tried in serializer
class TabSerializer(serializers.ModelSerializer):
hi = serializers.CharField(source='name_en')
en = serializers.CharField(source='name_en')
class Meta:
model = Tab
fields =('id','name_en','name_hi')
It just return id name_en and name_hi irrespective of hi ,en and checked.

You set it in serializer for column alias
For column table alias
class TabSerializer(serializers.ModelSerializer):
hi = serializers.CharField(source='name_hi')
en = serializers.CharField(source='name_en')
class Meta:
model = TabFaultOption
fields =('id','hi','en')
Now for column which does not exist in the database you need to change in the related model
model.py
class Tab(models.Model):
id = models.IntegerField()
name_hi = models.CharField(max_length=1000)
name_en = models.CharField(max_length=1000)
checked=False
class Meta:
managed = False
db_table = 'tab'
Now in serializer include the checked column
class TabSerializer(serializers.ModelSerializer):
hi = serializers.CharField(source='name_en')
en = serializers.CharField(source='name_en')
checked= false
class Meta:
model = Tab
fields =('id','hi','en','checked')

Related

How to create Article tags from splitting the Title in Django

I want to create articles tags from the title of a RSS feed post. Then save the tags into a DB with a post_id of the title i got the tags from at the same time. Something like this:
Title = "Voyant raises $15M to scale production of its tiny, inexpensive lidar tech"
Tags = ['Voyant', 'Raises', '$15M', 'To', 'Scale', 'Production', 'Of', 'Its', 'Tiny', 'Inexpensive', 'Lidar', 'Tech']
Assuming the post_id is 1, the Tags table should look like:
id | tag | post_id
--------------------------------
1 | Voyant | 1
2 | Raises | 1
I have 3 models in my table(Source, Posts & Tags).
class Source(models.Model):
name = models.CharField(max_length=500, verbose_name='Website Name')
class Posts(models.Model):
post_title = models.CharField(max_length=500, verbose_name='Post Title')
source = models.ForeignKey(Source, on_delete=models.CASCADE, verbose_name='Source')
class Tags(models.Model):
name = models.CharField(max_length=500)
post = models.ForeignKey(Posts, on_delete=models.CASCADE, verbose_name='Posts')
So so far i was able to split the title above.
title = item.title
strip_away = title.replace(",", "").replace(":", "").replace("(", "").replace(")", "").replace("'", "").replace("[", "").replace("]", "").replace("!", "").replace("?", "").replace("-", " ")
capital = strip_away.title()
article_tags = capital.split()
But now my problem comes during the saving part.
def fetch_articles():
feed = feedparser.parse("my_site_of_preference")
source = Source.objects.get(pk=1)
source_id = int(source.pk)
source_name = source
save_new_articles(source_id, source_name, feed)
def save_new_articles(source_id, source_name, feed):
selected_source_id = source_id
for item in feed.entries:
title = item.title
""" The splitting code """
if not Posts.objects.filter(post_title=title).exists():
post = Posts(post_title = title, source_id = selected_source_id)
post.save()
for i in range(len(article_tags)):
tags = Tags.objects.create(name = article_tags[i], post_id = source_name.pk)
tags.save()
I keep getting the error:
django.db.utils.IntegrityError: insert or update on table "Posts_tags" violates foreign key constraint "Posts_tags_post_id_3e6ae939_fk_Posts_posts_id"
DETAIL: Key (post_id)=(1) is not present in table "Posts_posts".
The post hasn't been saved to create a post_id that it can be used as a PK when saving the tags. How can i go about this to save the tags after saving the post title?
When saving tags, you should reference the post with the object, not the pk of it. Django ORM will do that for you. And when using create, you do not need to save it again as create() already saves it. Try the following within your loop:
Tags.objects.create(name=article_tags[i], post=post)

Django sending values of object with foreign key

I have a app that have 2 models:
Projecto Model's
class Projeto(models.Model):
field1 = ........
field2 = ........
Aditamento Model's
class Aditamento(models.Model):
processo = models.ForeignKey(Projet, on_delete=models.CASCADE,verbose_name="Projecto",related_name='ProcessoObjects')
field1 = .....
field2 = ....
Projecto Admin
class AditamentoInline(admin.StackedInline):
form = AditamentoForm
model = Aditamento
extra = 0
max_num = 4
class ProjetoAdmin(admin.ModelAdmin):
inlines = [AditamentoInline]
I can have 1 projeto with several aditamento's ( max:4)
Right now i want to send the field's of each aditamento to a page html to print.
when i open my object project i have 4 buttons , and when i click on of them , i want to send the fields of that aditamento corresponding that object i open.
So if i click in 3-aditamento i will send the values of aditamento i create in third and so for all.
What is the best way to do this ?

Django trying to add "_id" to the primary key OneToOne column

Just started Django.
I have 2 models. Radusergroup and expiration. username is primary key on Radusergroup and a OnetoOne Field in expiration with primary_key=True. Django is trying query for username_id in expiration model although the field itself is username only.
When I dont explicitly define Managed=False it also tries to change the username field in expiration table from the database to username_id as well.
What am I doing wrong here ?
class Radusergroup(models.Model):
username = models.CharField(max_length=64,primary_key=True)
groupname = models.CharField(max_length=64)
priority = models.IntegerField()
class Meta:
managed = False
class expiration(models.Model):
username = models.OneToOneField(Radusergroup,on_delete=models.CASCADE, to_field='username', primary_key=True)
expiration = models.DateTimeField()
class Meta:
managed = False
python .\manage.py shell
>>> help(expiration())
Help on expiration in module panel_app.models object:
class expiration(django.db.models.base.Model)
| expiration(*args, **kwargs)
|
| expiration(username, expiration)
|
| Method resolution order:
| expiration
| django.db.models.base.Model
| builtins.object
|
| Methods defined here:
|
| expiration = <django.db.models.query_utils.DeferredAttribute object>
| get_next_by_expiration = _method(self, *, field=<django.db.models.fields.DateTimeField: expiration>, is_next=True, **
kwargs)
|
| get_previous_by_expiration = _method(self, *, field=<django.db.models.fields.DateTimeField: expiration>, is_next=Fals
e, **kwargs)
|
| username_id = <django.db.models.query_utils.DeferredAttribute object>
| ----------------------------------------------------------------------
Thanks dirkgroten for pointing me to the right direction.
Adding db_column solved my problem
class expiration(models.Model):
username = models.OneToOneField(Radusergroup,on_delete=models.PROTECT, to_field='username',db_column="username" , primary_key=True)

serializer.DictField does not save to database

I have this model:
class x(model.Models):
name = models.CharField(max_length=50, unique=True)
y = models.ManyToManyField(Y, related_name='y', db_table='x_y',
blank=False,null=False)
and this serializer:
class Serializer(DynamicFieldsModelSerializer):
class Meta:
model = models.x
fields = '__all__'
when I post data to this model I need to set this fields:
'name':['some name'],'y':['1','2']
this will make a row in database x with:
id | name
1 | some name
and two row in database x_y with:
id| x_id | y_id
1 | 1 | 1
2 | 1 | 2
the problem is that front end dose not send me 'name' and 'y' ,but send me 'name' and 'y[]', so in order to get data I needed to add this to my serializer class:
y= serializers.DictField(child=serializers.IntegerField(min_value=0, max_value=2))
but the result is that no data will save in x_y table.I dont know how to solve this
One issue that stands out to me is that you're using a DictField to handle a list of integers.
Presuming the integers are actually the primary key of your Y model, have you tried using y = PrimaryKeyRelatedField(many=True)? This seems like what you would be after.

django accessing raw many to many created table fields

Model:
class Subjects (models.Model):
name = models.CharField(max_length=100)
places = models.CharField(max_length=100)
class Student (models.Model):
name = models.CharField(max_length=40)
lastname = models.CharField(max_length=80)
subjects = models.ManyToManyField(Subjects, blank=True)
Django creates appname_student_subjects when I use model above.
appname_student_subjects table looks for example, like this:
id | student_id | subjects_id
-----------------------------------------
1 | 1 | 10
2 | 4 | 11
3 | 4 | 19
4 | 5 | 10
...
~1000
How can I access subjects_id field and count how many times subjects_id exists in the table above (and then do something with it). For example: If subject with id 10 exists two times the template displays 2. I know that I should use "len" with result but i don't know how to access subject_id field.
With foreign keys I'm doing it like this in a for loop:
results_all = Students.objects.filter(subject_id='10')
result = len(results_all)
and I pass result to the template and display it within a for loop but it's not a foreign key so it's not working.
You can access the through table directly.
num = (Students.subjects # M2M Manager
.through # subjects_students through table
.objects # through table manager
.filter(student_id=10) # your query against through table
.count())