Please help to understand how to correct limit for "team" field by "company" team?
It's my code :
class CustomCompany(models.Model):
company_name = models.CharField(max_length=30,
default="None",
unique=True
)
class CustomTeam(models.Model):
team_name = models.CharField(
max_length=30,
default="None"
)
company_name = models.ForeignKey(CustomCompany,
on_delete=models.CASCADE,
related_name='company_name+',
to_field='id',
)
class CustomUser(AbstractUser):
phone = models.CharField(max_length=20, blank=True)
company = models.ForeignKey(CustomCompany,
on_delete=models.CASCADE,
default='None',
to_field='company_name',
related_name='company'
)
team = models.ForeignKey(CustomTeam,
on_delete=models.CASCADE,
default=1,
related_name='team_name+',
limit_choices_to={"company_name_id":"company_id"},
)
And problem in last string (limit_choices_to)
How to correct do this, limit teams by company?
Current error, if it's required the next :
invalid literal for int() with base 10: 'company_id'
Considering that CustomTeam already belongs to a CustomCompany, have you considered dropping the field CustomUser.company and just using CustomUser.team.company ?
The models stay almost the same:
class CustomCompany(models.Model):
...
class CustomTeam(models.Model):
...
company = models.ForeignKey(CustomCompany, ...)
class CustomUser(AbstractUser):
...
team = models.ForeignKey(CustomTeam, ...)
A few notes:
a ForeingKey should not have a int as default value, it has to be a model instance; I would just leave the default out of the model definition.
Related
I have 2 models, and I wanted to search with a Many to Many field according to my structuring, below is my models :
class User(django_models.AbstractBaseUser, TimeStampedModel,
django_models.PermissionsMixin):
"""
User model for the user creation
"""
uuid = models.UUIDField(unique=True, max_length=500,
default=uuid.uuid4,
editable=False,
db_index=True, blank=False, null=False)
account_types = models.ManyToManyField(AccountTypes,
related_name='account_types')
Then another model AccountTypes :
class AccountTypes(TimeStampedModel, models.Model):
"""
Account types for the users. e.g Mentors, Mentees, Parents etc.
"""
uuid = models.UUIDField(unique=True, max_length=500,
default=uuid.uuid4,
editable=False,
db_index=True, blank=False, null=False)
name = models.CharField(_('Account Name'), max_length=30, blank=False,
null=False)
How can I search a user uuid with the certain AccountType ?
My try was like this :
User.objects.get(uuid=uuid, account_types__in=['Mentor'])
But I got this error :
ValueError: Field 'id' expected a number but got 'Mentor'.
You should filter on the name of the account_types, so:
User.objects.get(uuid=uuid, account_types__name='Mentor')
or if you want all User objects that are a mentor, you can work with:
User.objects.filter(account_types__name='Mentor')
can not access foreignkey related objects , showing error
i have crated instance of Hospital and Availablity , But while querying using H1.availablity_set.all()
//error
'Hospital' object has no attribute 'availablity_set'
models.py
class Hospital(models.Model):
name = models.CharField(max_length = 256)
address = models.CharField(max_length=256,null=True, blank=True)
phone = models.CharField(max_length=10)
city = models.ForeignKey(City, on_delete=models.CASCADE, related_name = 'City')
def __str__(self):
return self.name
class Availablity(models.Model):
hospital = models.ForeignKey(Hospital, on_delete = models.CASCADE, related_name='availablities')
facility = models.ForeignKey(Facility, on_delete= models.CASCADE, related_name='facilities')
updated_at = models.DateTimeField(auto_now=True)
total = models.IntegerField(default=0)
available = models.IntegerField(default=0)
code
For your hospital field of the Availablity (sec), you used related_name='availablities' [Django-doc], this is the name of the relation in reverse, you thus access the Availabilitys for a Hospital:
my_hospital.availablities.all()
Your model classes and related names have some spelling mistakes. Consider renaming Availablity to Availability, related_name='availablities' to related_name='availabilities'. Furthermore it (usually) does not make much sense to give the related_name the same name is the ForeignKey itself, since that is how you query in reverse. It is thus better to rename the relaed_name to:
class Hospital(models.Model):
# …
city = models.ForeignKey(
City,
on_delete=models.CASCADE,
related_name='city_hospitals'
)
I have two models in Django with managed=False, because they are generated by SQL.
Django's Querysets based on these models do not generate the SQL queries they should. They add an '_ID' suffix to a column name that I never specified. This causes the queries to fail.
The models:
class MaterialsPerBatch(models.Model):
BATCH = models.CharField(null=False, max_length=255)
MATERIAL = models.ForeignKey('ColumnsPerMaterialStatic', on_delete=models.CASCADE)
class Meta:
db_table = "CDH_MATERIALS_PER_BATCH"
managed = False
class ColumnsPerMaterialStatic(models.Model):
MATERIAL = models.CharField(primary_key=True, null=False, max_length=255)
MATERIAL_LINK = models.CharField(null=False, max_length=255)
class Meta:
db_table = "CDH_COL_PER_MAT_STATIC"
managed = False
I want to filter the first model by BATCH, and find all corresponding second models that share the MATERIAL field.
The query looks like this:
qs = models.MaterialsPerBatch.objects.filter(
BATCH__in=['foo', 'bar']).values('BATCH', 'MATERIAL__MATERIAL_LINK')
I get this error: "django.db.utils.DatabaseError: ORA-00904: CDH_MATERIALS_PER_BATCH"."MATERIAL_ID": invalid identifier"
Inspecting qs.query shows that Django runs the following query in the background:
SELECT "CDH_MATERIALS_PER_BATCH"."BATCH", "CDH_COL_PER_MAT_STATIC"."MATERIAL_LINK"
FROM "CDH_MATERIALS_PER_BATCH"
INNER JOIN "CDH_COL_PER_MAT_STATIC"
ON ("CDH_MATERIALS_PER_BATCH"."MATERIAL_ID" = "CDH_COL_PER_MAT_STATIC"."MATERIAL")
WHERE "CDH_MATERIALS_PER_BATCH"."BATCH" IN ('foo', 'bar')
So the question is, why does Django turn "CDH_MATERIALS_PER_BATCH"."MATERIAL" into "CDH_MATERIALS_PER_BATCH"."MATERIAL_ID"?
I never specified any '_ID' suffix.
How do I tell Django not to add that suffix?
Django allows the db_column name to be specified, so it will not assume the _id is part of the name.
class MaterialsPerBatch(models.Model):
BATCH = models.CharField(null=False, max_length=255, db_column='BATCH')
MATERIAL = models.ForeignKey('ColumnsPerMaterialStatic', on_delete=models.CASCADE)
class Meta:
db_table = "CDH_MATERIALS_PER_BATCH"
managed = False
class ColumnsPerMaterialStatic(models.Model):
MATERIAL = models.CharField(primary_key=True, null=False, max_length=255, db_column='MATERIAL')
MATERIAL_LINK = models.CharField(null=False, max_length=255)
class Meta:
db_table = "CDH_COL_PER_MAT_STATIC"
managed = False
You specify the name of the column with the db_column=… parameter [Django-doc]:
class MaterialsPerBatch(models.Model):
BATCH = models.CharField(null=False, max_length=255)
MATERIAL = models.ForeignKey(
'ColumnsPerMaterialStatic',
on_delete=models.CASCADE,
db_column='MATERIAL'
)
class Meta:
db_table = 'CDH_MATERIALS_PER_BATCH'
managed = False
Normally the names of the fields are written in snake_case, not SCREAMING_SNAKE_CASE, so you might want to consider renaming BATCH and MATERIAL to batch and material and thus use the db_column to specify the name of the database column:
class MaterialsPerBatch(models.Model):
batch = models.CharField(
max_length=255,
db_column='BATCH'
)
material = models.ForeignKey(
'ColumnsPerMaterialStatic',
on_delete=models.CASCADE,
db_column='MATERIAL'
)
# …
at the moment I try to get recipes from my API. I have a Database with two tables one is with recipes and their ids but without the ingredients, the other table contains the ingredients and also the recipe id. Now I cant find a way that the API "combines" those. Maybe its because I added in my ingredient model to the recipe id the related name, but I had to do this because otherwise, this error occurred:
ERRORS:
recipes.Ingredients.recipeid: (fields.E303) Reverse query name for 'Ingredients.recipeid' clashes with field name 'Recipe.ingredients'.
HINT: Rename field 'Recipe.ingredients', or add/change a related_name argument to the definition for field 'Ingredients.recipeid'.
Models
from django.db import models
class Ingredients(models.Model):
ingredientid = models.AutoField(db_column='IngredientID', primary_key=True, blank=True)
recipeid = models.ForeignKey('Recipe', models.DO_NOTHING, db_column='recipeid', blank=True, null=True, related_name='+')
amount = models.CharField(blank=True, null=True, max_length=100)
unit = models.CharField(blank=True, null=True, max_length=100)
unit2 = models.CharField(blank=True, null=True, max_length=100)
ingredient = models.CharField(db_column='Ingredient', blank=True, null=True, max_length=255)
class Meta:
managed = True
db_table = 'Ingredients'
class Recipe(models.Model):
recipeid = models.AutoField(db_column='RecipeID', primary_key=True, blank=True) # Field name made lowercase.
title = models.CharField(db_column='Title', blank=True, null=True, max_length=255) # Field name made lowercase.
preperation = models.TextField(db_column='Preperation', blank=True, null=True) # Field name made lowercase.
images = models.CharField(db_column='Images', blank=True, null=True, max_length=255) # Field name made lowercase.
#ingredients = models.ManyToManyField(Ingredients)
ingredients = models.ManyToManyField(Ingredients, related_name='recipes')
class Meta:
managed = True
db_table = 'Recipes'
When there is no issue it has to be in the serializer or in the view.
Serializer
class IngredientsSerializer(serializers.ModelSerializer):
# ingredients = serializers.CharField(source='ingredients__ingredients')
class Meta:
model = Ingredients
fields = ['ingredient','recipeid']
class FullRecipeSerializer(serializers.ModelSerializer):
ingredients = IngredientsSerializer(many=True)
class Meta:
model = Recipe
fields = ['title','ingredients']
View
class FullRecipesView(generics.ListCreateAPIView):
serializer_class = FullRecipeSerializer
permission_classes = [
permissions.AllowAny
]
queryset = Recipe.objects.all()
This is at the moment my output
But I want e.g. the recipe with id 0 and all the ingredients which have also recipe id 0.
I really hope that you can help me. Thank you so much!
From the doc of ForeignKey.related_name,
If you’d prefer Django not to create a backwards relation, set related_name to '+' or end it with '+'.
So, change the related_name of Ingredients.recipeid field to
class Ingredients(models.Model):
# rest of the fields
recipeid = models.ForeignKey(
'Recipe',
models.DO_NOTHING,
db_column='recipeid',
blank=True,
null=True,
related_name="ingredients_ref" # Changed the related name
)
Then, migrate the database using python manage.py makemigrations and python manage.py migrate
Then, update your FullRecipeSerializer class as,
class FullRecipeSerializer(serializers.ModelSerializer):
ingredients_forward = IngredientsSerializer(many=True, source="ingredients")
ingredients_backward = IngredientsSerializer(many=True, source="ingredients_ref")
class Meta:
model = Recipe
fields = ['title', 'ingredients_forward', 'ingredients_backward']
Note that, here I have added two fields named ingredients_forward and ingredients_backward because there existing two types of relationships between Recipe and Ingredients and I am not sure which one you are seeking.
I've tried reading the docs and previous answers to this question without much luck.
I've got a bunch of student-course registrations and I'd like to see some of those selected registrations in conjunction with some of the attributes of the students. No luck so far...I'd request your advice!
Here's the model:
class Student(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
netID = models.CharField(max_length=8)
class Registration(models.Model):
student = models.ForeignKey(Student)
course = models.ForeignKey(Course)
attendance_M = models.BooleanField(default=False)
attendance_Tu = models.BooleanField(default=False)
and here is the tables.py:
class AttendanceTable(tables.Table):
netID = tables.Column(accessor='Student.netID')
first = tables.Column(accessor='Student.first_name')
last = tables.Column(accessor='Student.last_name')
class Meta:
model = Registration
attrs = {"class": "paleblue"}
fields = ('attendance_M', 'attendance_Tu',)
sequence = ('netID', 'first', 'last', 'attendance_M', 'attendance_Tu',)
While I'm getting data on the attendance values, there's nothing from the student foreign columns.
netID First Last Attendance M Attendance Tu
— — — ✔ ✘
And it's the same deal if I start the Table with model = Student and use accessors against the Registration table, it's the same deal.
I feel like I'm missing something very conceptual and crucial -- please guide me!
The model name in the accessor parameter of the column should be lowercase.
Use accessor='student.netID' instead of accessor='Student.netID'.
When using the accessor parameter, you have to use the field name stated in the Model that has the foreign key, and then select which field from that table you want to use.
So, for these models:
#models.py
class Description_M(models.Model):
id_hash = models.CharField(db_column='Id_hash', primary_key=True, max_length=22)
description = models.CharField(db_column='Description', max_length=255, blank=True, null=True)
class GeoCodes(models.Model):
geo = models.CharField(db_column='Geo', primary_key=True, max_length=5)
city_name = models.CharField(db_column='City', max_length=150, blank=True, null=True)
class RefSources(models.Model):
id_source = models.IntegerField(db_column='Id_source', primary_key=True,)
source_name = models.CharField(db_column='Source', max_length=150, blank=True, null=True)
class Price(models.Model):
id_hash = models.ForeignKey(Description_M, models.DO_NOTHING, db_column='Id_hash')
date= models.ForeignKey(DateTime, models.DO_NOTHING, db_column='Date')
geo = models.ForeignKey(GeoCodes, models.DO_NOTHING, db_column='Geo')
id_source = models.ForeignKey(RefSources, models.DO_NOTHING, db_column='Id_source') # Field name made lowercase.
price = models.FloatField(db_column='Price',primary_key=True, unique=False,default=None)
When using the foreign key to pull fields from that table, you have to:
class price_table(tables.Table):
description = tables.Column(accessor = 'id_hash.description')
city = tables.Column(accessor = 'geo.city_name')
source = tables.Column(accessor = 'id_source.source_name')
class Meta:
model = Price
fields = ['date','price']
sequence = ['description ','date','city ','source','price']
template_name = 'django_tables2/bootstrap.html'