Check if item exists in database by field value - django

I have a class called Product and I want to check if there is already a product in the database with the same title.
class Product(models.Model):
title = models.CharField(max_length=255)
...
for (something in something):
check if db contains product with a title of 'Some Product'

You can work with .exists() [Django-doc]:
Product.objects.filter(title='Some Product').exists()
It might however be better to enforce uniqness at the database level, with unique=True [Django-doc]:
class Product(models.Model):
title = models.CharField(max_length=255, unique=True)
then if the database enforces (most databases do), it will simply be impossible to create a new Product with the same title.
You can also obtain a Product, or create it if it does not yet exists, with .get_or_create(…) [Django-doc]:
my_prod, created = Product.objects.get_or_create(title='Some Product')

Related

Can't add to ManyToManyField in Django custom task

I have two models in my Django app (Tag and MyModel).
MyModel has a ManyToManyField (tags) that uses the Tag model
class Tag(models.Model):
CATEGORY_CHOICES = (
('topic', 'topic')
)
tag = models.CharField(max_length=100, unique=True)
category = models.CharField(max_length=100, choices=CATEGORY_CHOICES)
class MyModel(models.Model):
id = models.CharField(max_length=30, primary_key=True)
title = models.CharField(max_length=300, default='')
author = models.CharField(max_length=300)
copy = models.TextField(blank=True, default='')
tags = models.ManyToManyField(Tag)
I have a custom Django management task where I delete the Tags table, get new data, and refresh the Tags table with bulk_create
Tag.objects.all().delete()
....get new data for Tag table
Tag.objects.bulk_create(new_tags)
However after this - if I try to add a tag to an instance of MyModel.tags...
mymodel_queryset = MyModel.objects.all()
for mymodel in mymodel_queryset
mymodel.tags.add(5)
...I get this error:
CommandError: insert or update on table "bytes_mymodel_tags" violates foreign key constraint ....
DETAIL: Key (tag_id)=(5) is not present in table "bytes_tag".
It seems like the Tag table is empty even though I just updated it
For some reason deleting and resetting the Tag table prevents me from adding to an instance of MyModel.tags. How can I do this?
Note: If I don't first delete and reset the Tags table then I can add to MyModel.tags just fine
Instead of adding random number in mymodel.tags.add you have to add Tag object.
mymodel_queryset = MyModel.objects.all()
for mymodel in mymodel_queryset
mymodel.tags.add(new_tags)
Im expanding a little bit on what has already been said here above:
When you have a m2m relationship, if you want to create a new row in the through table by using add you have to do so by adding an instance of the corresponding class connected through the relationship.
So if you have Tag and MyModel and you want to add a Tag object to MyModel, you have to first create a MyModel instance and then add to it a Tag instance.
For example:
tag_1 = Tag.objects.create(tag="test", category="test")
my_model_1 = MyModel.objects.create(title="my Title", author="me", copy="xxx")
# This is how you do it
my_model_1.add(tag_1)
Et voilà!
Note that when you use .add(instance) the save() method is built-in so you don't need to call it.

Django: Annotate with field from another table (one-to-many)

Good day.
I wish to annotate my model with information from a different table.
class CompetitionTeam(models.Model):
competition_id = models.ForeignKey('Competition', on_delete=models.CASCADE, to_field='id', db_column='competition_id')
team_id = models.ForeignKey('Team', on_delete=models.CASCADE, to_field='id', null=True, db_column='team_id')
...
class Team(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
teamleader_id = models.ForeignKey('User', on_delete=models.CASCADE, to_field='id', db_column='teamleader_id')
...
class Competition(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
...
Looping through my competitions, I wish to retrieve the list of competitionteam objects to be displayed with the relevant team's name. I tried:
CompetitionTeam.objects.filter(competition_id=_competition.id).filter(team_id__in=joined_team_ids).annotate(name=...)
-where instead of the ellipses I put Subquery expressions in. However, I'm unsure of how to match the team_id variable. eg.
*.anotate(name=Subquery(Team.objects.filter(id=competitionteam.team_id)).values('name'))
Related is the question: Django annotate field value from another model but I am unsure of how to implement that in this case. In that case, in place of mymodel_id, I used team_id but it only had parameters from the Team object, not my competition team object. I didn't really understand OuterRef but here is my attempt that failed:
CompetitionTeam.objects.filter(competition_id=_competition.id).filter(team_id__in=joined_team_ids).annotate(name=Subquery(Team.objects.get(id=OuterRef('team_id'))))
"Error: This queryset contains a reference to an outer query and may only be used in a subquery."
The solution for my question was:
CompetitionTeam.objects.filter(
competition_id=_competition.id,
team_id__in=joined_team_ids
).annotate(
name=Subquery(
Team.objects.filter(
id=OuterRef('team_id')
).values('name')
))
Thanks.

Setting default value of field in model to another model instance

Model
class SlackPermission(models.Model):
#fields
class GithubPermission(models.Model):
#fields
class Employee(models.Model):
#fields
slack_permission = models.OneToOneField(SlackPermission, on_delete=models.CASCADE, related_name='Slack',default=SlackPermission.objects.get(pk=1))
github_permission = models.OneToOneField(GithubPermission, on_delete=models.CASCADE, related_name='Github',default=GithubPermission.objects.get(pk=1))
Error:
ValueError: Cannot serialize: <GithubPermission: GithubPermission object (1)>
There are some values Django cannot serialize into migration files.
I am creating API just to create Employee. Where there is not option of giving slackpermissions and githubpermissions. How do I give default value in there?
The problem is that the default is calculated immediately, and for migrations, it can not really serialize that.
That bing said, it is not very useful to do this anyway. You can just pass the primary key as default value. This is specified in the documentation on the default=… parameter [Django-doc]:
For fields like ForeignKey that map to model instances, defaults should be the value of the field they reference (pk unless to_field is set) instead of model instances.
So we can write this as:
class Employee(models.Model):
full_name = models.CharField(max_length=100)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
slack_permission = models.OneToOneField(
SlackPermission,
on_delete=models.CASCADE,
related_name='Slack',
default=1
)
github_permission = models.OneToOneField(
GithubPermission,
on_delete=models.CASCADE,
related_name='Github',
default=1
)
Note that you should ensure that there exists an object with that primary key. Therefore it might not be ideal to do that.
The issue here is that you are attempting to set a field value to an object instance. So your default value should be just 1 if you are certain of the pk.
Also, I am not sure the advantage of creating two separate models for these permission values. Seems like they can just be fields in your employee model. Seems like these permissions share identical fields as well which will allow you to flatten them a bit.

How to use select_related

How do I use select_related to get the first and last name of the employee class below.
class Employee(models.Model):
"""
Model, which holds general information of an employee.
"""
user = models.OneToOneField(User, related_name='users',
on_delete=models.CASCADE, unique=True)
photo_logo = models.FileField(null=True, blank=True)
Here is how I have implemented my query
emp=Employee.objects.filter(pk=1).select_related('user').values('user_first_name','user_last_name','id')
But I get the following logs after running a print statement in django shell
Cannot resolve keyword 'user_first_name' into field. Choices are: address, address_id, attendance, basic,
Since you need specific fields of user model, you dont need select_related in this case, just use:
emp=Employee.objects.filter(pk=1).values('user__first_name','user__last_name','id')
query.
Note that you shoulduse double underscore __ to perform join.
We should use __ for relation field
emp=Employee.objects.filter(pk=1).select_related(
'user'
).values('user__first_name','user__last_name','id')

How to create a unique_for_field slug in Django?

Django has a unique_for_date property you can set when adding a SlugField to your model. This causes the slug to be unique only for the Date of the field you specify:
class Example(models.Model):
title = models.CharField()
slug = models.SlugField(unique_for_date='publish')
publish = models.DateTimeField()
What would be the best way to achieve the same kind of functionality for a non-DateTime field like a ForeignKey? Ideally, I want to do something like this:
class Example(models.Model):
title = models.CharField()
slug = models.SlugField(unique_for='category')
category = models.ForeignKey(Category)
This way I could create the following urls:
/example/category-one/slug
/example/category-two/slug
/example/category-two/slug <--Rejected as duplicate
My ideas so far:
Add a unique index for the slug and categoryid to the table. This requires code outside of Django. And would the built-in admin handle this correctly when the insert/update fails?
Override the save for the model and add my own validation, throwing an error if a duplicate exists. I know this will work but it doesn't seem very DRY.
Create a new slug field inheriting from the base and add the unique_for functionality there. This seems like the best way but I looked through the core's unique_for_date code and it didn't seem very intuitive to extend it.
Any ideas, suggestions or opinions on the best way to do this?
What about unique_together?
class Example(models.Model):
title = models.CharField()
slug = models.SlugField(db_index=False)
category = models.ForeignKey(Category)
class Meta:
unique_together = (('slug','category'),)
# or also working since Django 1.0:
# unique_together = ('slug','category',)
This creates an index, but it is not outside of Django ;) Or did I miss the point?