Django ManyToMany not appearing on pgAdmin - django

I've created (abridged) two tables:
class Tag(models.Model):
tag_word = models.CharField(max_length=35)
slug = models.CharField(max_length=250)
def __unicode__(self):
return self.word
Class Place(models.Model):
place_name = models.CharField(max_length=200)
...
tag_word = models.ManyToManyField(Tag)
I can see my Tags field on Django Admin, but not on PgAdmin and they don't return in my Place queryset. What have missed?
Thanks!

As pointed out by #karthikr in the comments, this data appears separately from the main table itself.
It is stored in another table and the name should be something like <appname>_place_tag_word for the above example. Or <appname>_<tablename>_<columnname> more generically.

Related

Syntax to reverse-query a cached queryset

I have the following 3 models related by Foreign Key as following:
class Seller(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class Genre(models.Model):
seller= models.ForeignKey(Seller, related_name="genre", on_delete=models.CASCADE)
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class Book(models.Model):
genre= models.ForeignKey(Genre, related_name="book", on_delete=models.CASCADE)
name = models.CharField(max_length=20)
def __str__(self):
return self.name
And I want to retrieve the whole 3 tables in one database query, by querying the Seller objects, as following:
sellers = Seller.objects.select_related('genre', 'book').all().values('name')
seller_df = pd.DataFrame(list(sellers))
What is the syntax to filter for books carried by a particular seller, without hitting the database again (by utilizing either the Seller queryset or the pandas seller_df)
seller1 = seller_df ['name'].iloc[0]
seller1_books = Book.objects.filter(...)
seller_last = seller_df ['name'].iloc[-1]
seller_last_books = Book.objects.filter(...)
I dont know so mach about caching but I know something that you like:
We use select_related when the object is single like onetoone or fk.
.
for many to many or reverse fk like your example use prefetch_related

Edit multiselect field?

So I have a ManyToMany field in my model and Django admin renders it as a multiselect field. It works fine and I have no issues — except that I can't Edit it after creating a record.
I tried Del key, mouse right-click, nothing worked. Looks like I have to delete the record and create it again?
This is the field I want to edit. I want to remove one or two of the above items. I'm on Windows.
Well it looks like there's a simpler solution:
(Courtesy of Webdev Hints)
Here's my models:
class Technology(models.Model):
title = models.CharField(max_length=10)
def __str__(self):
return self.title
class Meta:
verbose_name_plural = 'Technologies'
class Project(models.Model):
title = models.CharField(max_length=100)
description = HTMLField()
technology = models.ManyToManyField(Technology, related_name='projects')
image = models.ImageField(upload_to='projects/')
def __str__(self):
return self.title
And the solution is to add the following to the admin.py:
#admin.register(Technology)
class TechnologyAdmin(admin.ModelAdmin):
pass
class TechnologyInline(admin.TabularInline):
model = Project.technology.through
#admin.register(Project)
class ProjectAdmin(admin.ModelAdmin):
inlines = (TechnologyInline,)
exclude = ('technology',)
Now the ManyToMany filed is editable.

django: Can not find the Data table row of the Extra field on many-to-many relationships?

Hello i am trying to understand Django Data Models and it´s possibilities. After using one-to-one and m2m i am now trying to understand the m2m extra fields. So i followed the Example of the Django Doc and populated the models with some Data.
models.py
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
def __str__(self):
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
So far everything is fine, but as i looked into the model tables, via pgAdmin 4 ( i am using PostgreSQL), i could not find any members column in the Group model. So i made a little visual of my model and some screenshots of pgAdmin, for better understanding.
As you can see Group has only a id and name column.
Question
my question: Is this m2m members relation of Group, only some kind of "virtual" created relation via the Membership.person.fk and Membership.group.fk? Meaning there is no field which will be populated? I try to imagine that it works like a recursive, instance query?

Custom column names in Intermediary table for many-to-many model in Django

Below is the code block of a Many-To-Many relationship between two models. Having searched and researched there appears to be no elegant way to create custom id column names for the foreign keys in the intermediary (or link) table that Django creates. The custom name using db_table='pizza_link_topping' creates the desired table name but the columns names in the table are not customizable it appears. Django automatically applied an _id to the end of the model name effectively making a column named topping_id and one called pizza_id.
What if I want custom names? Similar to how I can change the table name.
class Topping(models.Model):
topping_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
class Meta:
db_table = 'pizza_topping'
class Pizza(models.Model):
pizza_id = models.AutoField(primary_key=True) #custom id column name
topping = models.ManyToManyField(Topping, db_table='pizza_link_topping')
def __unicode__(self):
return self.title
class Meta:
db_table = 'pizza' #custom table name
https://docs.djangoproject.com/en/1.7/ref/models/fields/#django.db.models.Field.db_column
^Talks about using db_column but that only appears to work for only models.ForeignKey and not for models.ManyToManyField which is what I need.
I read about using through but that seams hackish and not really good...
https://docs.djangoproject.com/en/1.7/ref/models/fields/#django.db.models.ManyToManyField.through
Perhaps I don't understand fully how through works and it is the right way.
through is not so hackish. It does exactly what you want:
class Pizza(models.Model):
...
topping = models.ManyToManyField(Topping, through='PizzaLinkTopping')
class PizzaLinkTopping(models.Model):
pizza = models.ForeignKey(Pizza, db_column='pizza_noid')
topping = models.ForeignKey(Topping, db_column='topping_noid')
class Meta:
db_table = 'pizza_link_topping'

Model with Foreign keys not behaving as expected - Django

I have a model with two foreign keys to create many to many relationship - I am not using many to many field in Django
class Story(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.title
class Category(models.Model):
categoryText = models.CharField(max_length=50)
parentCat = models.ForeignKey('self',null=True,blank=True)
def __unicode__(self):
return self.categoryText
class StoryCat(models.Model):
story = models.ForeignKey(Poll,null=True,blank=True)
category = models.ForeignKey(Category,null=True,blank=True)
def __unicode__(self):
return self.story
I would like to query for a category like 'short', and retrieve all the unique keys to all stories returned.
>>>c=Category(categoryText='short')
>>>s=StoryCat(category=c)
when I try this I get errors "AttributeError: 'NoneType' object has no attribute 'title'. How can I do this?
I would like to query for a category like 'short', and retrieve all the unique keys to all stories returned.
c=Category.objects.get(categoryText='short')
story_ids = StoryCat.objects.filter(category=c).values_list('story')
And about your models:
Category name should probably be unique. And declare your many-to-many relation.
class Category(models.Model):
categoryText = models.CharField(max_length=50, unique=True)
stories = models.ManyToManyField(Story, through='StoryCat')
...
It makes no sense for intermediary table FK fields to be nullable. Also I assume the same story should not be added to the same category twice, so set a unique constraint.
class StoryCat(models.Model):
story = models.ForeignKey(Poll)
category = models.ForeignKey(Category)
class Meta:
unique_together = ('story', 'category')
The lines you're executing in the interpreter are not queries - they are instantiating new objects (but not saving them).
Presumably you meant this:
>>>c=Category.objects.get(categoryText='short')
>>>s=StoryCat.objects.get(category=c)