ChatGPT解决这个技术问题 Extra ChatGPT

Django admin ManyToMany inline "has no ForeignKey to" error

I'm setting up the Django admin to the following models:

class Tag(models.Model):                                                 
    name = models.CharField(max_length=100)                                 

class Quote(models.Model):                                                  
    author = models.CharField(max_length=100)                               
    quote = models.CharField(max_length=1000)                               
    tags = models.ManyToManyField(Tag)

With the following code:

class TagInline(admin.TabularInline):                                                                                               
    model = Tag                                                             
                                                                            
class QuoteAdmin(admin.ModelAdmin):                                         
    list_display = ('author', 'quote')                                      
    inlines = (TagInline,)                                                  
                                                                            
class TagAdmin(admin.ModelAdmin):                                           
    pass                                                                    
                                                                            
admin.site.register(Quote, QuoteAdmin)                                      
admin.site.register(Tag, TagAdmin)

When trying to view the admin page to add a Quote, the page shows an error saying <class 'quotes.models.Tag'> has no ForeignKey to <class 'quotes.models.Quote'>. This didn't happen before I added an inline. What's the problem? How do I correctly add a Tag as an inline?

(I spent a good 20 minutes searching for an answer; I found similar questions but none of their answers worked for me.)


C
Cat Plus Plus

Admin documentation has a section dedicated to inlining with many-to-many relationships. You should use Quote.tags.through as a model for TagInline, instead of Tag itself.


If I have a modal which has many manytomany field, that means for each one it needs a Inline and they are different?
@Rmatt For reversed many-to-many relations model = Tag.quote_set.related.through
Is there a trick for making the through model appear as a raw id field instead of listing very possible row in the DB?
and this is why I start to love Django
How to use filter_horizontal in that case? .through has no the model fields. So I get attribute error :(

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now