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 = False
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!
Rename ingredients to some other name in FullRecipeSerializer. It conflicts with ingredients in Recipe model. This should solve your issue. For example
class FullRecipeSerializer(serializers.ModelSerializer):
ingredients_recipe = IngredientsSerializer(many=True, source= 'ingredientid')
class Meta:
model = Recipe
fields = ['title','ingredients_recipe']
Related
I also need the field (commentGroupDesc) from the foreign keys objects.
models.py
class commentGroup (models.Model):
commentGroup = models.CharField(_("commentGroup"), primary_key=True, max_length=255)
commentGroupDesc = models.CharField(_("commentGroupDesc"),null=True, blank=True, max_length=255)
def __str__(self):
return str(self.commentGroup)
class Meta:
ordering = ['commentGroup']
class Comment (models.Model):
commentID = models.AutoField(_("commentID"),primary_key=True)
commentUser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
commentGroup = models.ForeignKey(commentGroup, on_delete=models.CASCADE, null=True)
commentCI = models.ForeignKey(Servicenow, on_delete=models.CASCADE, null=True)
commentText = RichTextField(_("commentText"), null=True, blank=True)
commentTableUpdated = models.CharField(_("commentTableUpdated"), null=True, blank=True, max_length=25)
def __str__(self):
return str(self.commentGroup)
class Meta:
ordering = ['commentGroup']
views.py
comment = Comment.objects.get(pk=commentID)
Here I get the commentGroup fine but I also need commentGroupDesc to put into my form.
At first, it's not a good thing to name same your model field as model name which is commentGroup kindly change field name, and run migration commands.
You can simply use chaining to get commentGroupDesc, also it's better to use get_object_or_404() so:
comment = get_object_or_404(Comment,pk=commentID)
group_desc = comment.commentGroup.commentGroupDesc
Remember to change field and model name first.
I got this code, but I can't find a way to create a view that retrieve the allergies a patient has.
class Patient(models.Model):
user = models.OneToOneField(User, related_name='patient', on_delete=models.CASCADE)
id_type = models.CharField(max_length=300)
id_number = models.CharField(max_length=300)
creation_date = models.DateField(default=datetime.date.today)
class Allergie(models.Model):
name = models.CharField(max_length=300, default="X")
class PatientAllergies(models.Model):
patient = models.ForeignKey(Patient, related_name="patient_allergies", on_delete=models.CASCADE)
allergie = models.ForeignKey(Allergie, on_delete=models.CASCADE, null=True)
professional_contract = models.ForeignKey(ProfessionalContract, null=True ,on_delete=models.CASCADE)
You can span a ManyToManyField relation over your PatientAllergies model that acts as a junction table:
class Patient(models.Model):
user = models.OneToOneField(User, related_name='patient', on_delete=models.CASCADE)
id_type = models.CharField(max_length=300)
id_number = models.CharField(max_length=300)
creation_date = models.DateField(auto_now_add=True)
allergies = models.ManyToManyField(
'Allergie',
through='PatientAllergies'
)
# …
You can then for a Patient object p with:
p.allergies.all()
An alternative is to filter the Allergie objects with:
Allergie.objects.filter(patientallergies__patient=p)
or with the ManyToManyField:
Allergie.objects.filter(patient=p)
I am a bit stumped as to how I can add multiple access_token and items_ids in Django Admin. The models and apps involved are as follows. This is my first post so please forgive if it isn't in proper format.
Trans/models.py
class Exchange(models.Model):
created = models.DateTimeField()
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='token', on_delete=models.CASCADE)
access_token = models.CharField(max_length=300, blank=True, default='')
item_id = models.CharField(max_length=300, blank=True, default='')
request_id = models.CharField(max_length=300, blank=True, default='')
class Meta:
ordering = ('item_id',)
I have setup a userprofile section for the admin:
Users/models.py
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, verbose_name='user', related_name='profile', on_delete=models.CASCADE)
avatar_url = models.CharField(max_length=256, blank=True, null=True)
dob = models.DateField(verbose_name="dob", blank=True, null=True)
public_token = models.CharField(max_length=100, blank=True, null=True, verbose_name='public_token')
access_token = models.CharField(max_length=100, blank=True, null=True, verbose_name='access_token')
item_id = models.CharField(max_length=100, blank=True, null=True, verbose_name='item_ID')
just_signed_up = models.BooleanField(default=True)
def __str__(self):
return force_text(self.user)
class Meta():
db_table = 'user_profile'
users/forms.py
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('user', 'public_token', 'access_token', 'item_id',)
users/admin.py
class UserProfileAdmin(admin.ModelAdmin):
search_fields = ('user', 'dob', 'public_token', 'access_token', 'item_id',)
ordering = ('user',)
list_select_related = ('user',)
admin.site.register(UserProfile, UserProfileAdmin)
class UserProfileAdminInline(admin.TabularInline):
model = UserProfile
I'm really just stumped as I tried making many to many field but couldnt seem to link correctly and or the process broke when testing in a sandbox environment. Any help would be greatly appreciated! In my case I need to record multiple access_tokens and item_ids for each user.
It's a little bit confusing what you are asking...particularly the way that your data model is setup....but I'm going to make a couple of assumptions in my answer (it would be helpful to better understand what you are trying to do at a high level).
I think what you are wanting to do is to be able to configure multiple Exchange objects per user profile...in which case I would set things up this way:
1. The related_name field on the FK to the user profile in the exchange model will be how you access multiple exchanges...so in this case you probably want a pluralized name.
2. To be able to edit multiple in the Django Admin you will need to setup an InlineAdmin object.
3. The CharFields that are actually ON the UserProfile will only ever be single fields...if you want multiple then you need to move them to another related object (like the Exchange model).
4. I don't think what you want here is a ManyToMany as that would imply user's would be sharing these tokens and item ids (or Exchanges?)...but maybe that is what you want...in which case you should change the ForeignKey to UserProfile from the Exchange model to a ManyToManyField. The rest of this post assumes you don't want that.
trans/models.py
from django.db import models
from django.conf import settings
class Exchange(models.Model):
class Meta:
ordering = ('item_id', )
created = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='exchanges', on_delete=models.CASCADE)
access_token = models.CharField(max_length=300, blank=True)
item_id = models.CharField(max_length=300, blank=True)
request_id = models.CharField(max_length=300, blank=True)
users/models.py
from django.db import models
from django.conf import settings
class UserProfile(models.Model):
class Meta:
db_table = 'user_profile'
user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, verbose_name='user', related_name='profile', on_delete=models.CASCADE)
avatar_url = models.CharField(max_length=256, blank=True)
dob = models.DateField(verbose_name="dob", blank=True, null=True)
public_token = models.CharField(max_length=100, blank=True, null=True)
access_token = models.CharField(max_length=100, blank=True, null=True)
item_id = models.CharField(max_length=100, blank=True, null=True)
just_signed_up = models.BooleanField(default=True)
def __str__(self):
return force_text(self.user)
users/admin.py
from django.contrib import admin
from trans.models import Exchange
from users.models import UserProfile
class ExchangeAdminInline(admin.TabularInline):
model = Exchange
class UserProfileAdmin(admin.ModelAdmin):
inlines = (ExchangeAdminInline, )
search_fields = ('user', 'dob', 'public_token', 'access_token', 'item_id', )
ordering = ('user', )
list_select_related = ('user', )
admin.site.register(UserProfile, UserProfileAdmin)
There is a lot that you can do to configure the inlines to behave how you want...but that's the basics.
Based on my previous question and feedback I received I have redesigned my Models and need some feedback before I run the "syncdb".
My concerns are mostly ForeignKeys and the one ManyToManyField in the Restaurant table. Should also the ManyTomany field have the through='' value and what the value should be?
Any feedback is appreciated!
Models
class Restaurant(models.Model):
id = models.AutoField(primary_key=True, db_column='id')
name = models.CharField(max_length=50L, db_column='name', blank=True)
address = models.CharField(max_length=100L, blank=True)
city_id = models.ForeignKey('City', related_name="restaurant_city")
location_id = models.ForeignKey('Location', related_name="restaurant_location")
hood_id = models.ForeignKey('Hood', null=True, blank=True, related_name="restaurant_hood")
listingrole_id = models.ForeignKey('Listingrole', related_name="restaurant_listingrole")
cuisine_types = models.ManyToManyField('Cuisinetype', null=True, blank=True, related_name="restaurant_cuisinetype")
class Meta:
db_table = 'restaurant'
class City(models.Model):
id = models.AutoField(primary_key=True, db_column='id')
name = models.CharField(max_length=50L, db_column='city')
state = models.CharField(max_length=50L, db_column='state', blank=True, null=True)
class Meta:
db_table = 'city'
class Cuisinetype(models.Model):
id = models.AutoField(primary_key=True, db_column='id')
name = models.CharField(max_length=50L, db_column='cuisine', blank=True) # Field name made lowercase.
class Meta:
db_table = 'cuisinetype'
class Location(models.Model):
id = models.AutoField(primary_key=True, db_column='id')
name = models.CharField(max_length=50L, db_column='location', blank=False, null=False)
city = models.ForeignKey('City', related_name="location_city")
class Meta:
db_table = 'location'
class Hood(models.Model):
id = models.AutoField(primary_key=True, db_column='id')
name = models.CharField(max_length=50L, db_column='hood')
city = models.ForeignKey('City', related_name='hood_city')
location = models.ForeignKey('Location', related_name='hood_location')
class Meta:
db_table = 'hood'
class Listingrole(models.Model):
id = models.AutoField(primary_key=True, db_column='id')
name = models.CharField(max_length=50L, db_column='listingrole', blank=True) # Field name made lowercase.
class Meta:
db_table = 'listingrole'
....
Having into account the concept and meaning of coisine_types you don't have to make the relationship using through keyword. You use it (mostly) when there is some information about the relation it self.
According Django documentation:
The most common use for this option is when you want to associate extra data with a many-to-many relationship.
See explanation here: Extra fields on many-to-many relationships
How do I bring in the information from another model?
I have two models Article, and ArticleBody
Article containing the main info and ArticleBody containing a loop of body and image information
class Article(models.Model):
author = models.ForeignKey(User)
title = models.CharField(max_length=100)
excerpt = models.CharField(max_length=140, null=True, blank=True, help_text='A description no longer than 140 characters that explains what the article is about, important for SEO')
category = models.ManyToManyField(Category)
date_published = models.DateTimeField()
slug = models.SlugField(null=True)
status = models.CharField(choices=STATUS, max_length=2, default='DR')
tags = TagField(default='', null=True, blank=True, help_text='Just add a comma between the tags i.e. "My very important name, Hunting, Scope, Rifle"')
source_name = models.CharField(default='', blank=True, null=True, help_text='Outdoor Magazine', max_length=100)
source_url = models.URLField(verify_exists=False, max_length=200, null=True, blank=True, help_text='http://www.source.com/2011/01/long-name/')
class ArticleBody(ImageModel):
article = models.ForeignKey(Article)
body = models.TextField(verbose_name='', blank=True, null=True)
image = models.ImageField(storage=cloudfiles_storage, upload_to='articles', default='avatar-blank.jpg', verbose_name='', blank=True, null=True)
caption = models.CharField(max_length=80, null=True, blank=True)
In my api resources.py file I am trying to get the ArticleBody information into my NewsResource...
This is what I have so far.
class NewsBodyResource(ModelResource):
class Meta:
queryset = ArticleBody.objects.all()
resource_name = 'article_body'
class NewsResource(ModelResource):
class Meta:
queryset = Article.objects.filter(status='PU', date_published__lt=datetime.datetime.now).order_by('-date_published')
resource_name = 'news'
What is the correct TastyPIE way, of making changes so I can get a loop of ArticleBody into my NewsResource?
class NewsBodyResource(ModelResource):
class Meta:
queryset = ArticleBody.objects.all()
resource_name = 'article_body'
class NewsResource(ModelResource):
newsbodies = fields.ToManyField('yourapp.api.resources.NewsBodyResource', 'articlebody_set', full=True)
class Meta:
queryset = Article.objects.filter(status='PU', date_published__lt=datetime.datetime.now).order_by('-date_published')
resource_name = 'news'
The parameters to ToManyField represent the following respectively:
project-relative import path to the resource representing the set
the name of field if it's on the parent model or the related_name
attribute of the field if it's on the child model
whether or not to embed
the full data of each child into the feed (True) or just resource
links to each child (False)