Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Querying read-only view with no primary key

class dbview(models.Model):
    # field definitions omitted for brevity
    class Meta:
        db_table = 'read_only_view'

def main(request):
    result = dbview.objects.all()

Caught an exception while rendering: (1054, "Unknown column 'read_only_view.id' in 'field list'")

There is no primary key I can see in the view. Is there a workaround?

Comment:
I have no control over the view I am accessing with Django. MySQL browser shows columns there but no primary key.

like image 543
dmi Avatar asked Mar 03 '09 10:03

dmi


2 Answers

When you say 'I have no control over the view I am accessing with Django. MySQL browser shows columns there but no primary key.'

I assume you mean that this is a legacy table and you are not allowed to add or change columns?

If so and there really isn't a primary key (even a string or non-int column*) then the table hasn't been set up very well and performance might well stink.

It doesn't matter to you though. All you need is a column that is guaranteed to be unique for every row. Set that to be 'primary_key = True in your model and Django will be happy.

  • There is one other possibility that would be problemmatic. If there is no column that is guaranteed to be unique then the table might be using composite primary keys. That is - it is specifying that two columns taken together will provide a unique primary key. This is perfectly valid relational modelling but unfortunatly unsupported by Django. In that case you can't do much besides raw SQL unless you can get another column added.
like image 67
Andy Baker Avatar answered Oct 22 '22 03:10

Andy Baker


I have this issue all the time. I have a view that I can't or don't want to change, but I want to have a page to display composite information (maybe in the admin section). I just override the save and raise a NotImplementedError:

    def save(self, **kwargs):
        raise NotImplementedError()

(although this is probably not needed in most cases, but it makes me feel a bit better)

I also set managed to False in the Meta class.

    class Meta:
       managed = False

Then I just pick any field and tag it as the primary key. It doesn't matter if it's really unique with you are just doing filters for displaying information on a page, etc.

Seems to work fine for me. Please commment if there are any problems with this technique that I'm overlooking.

like image 17
David S Avatar answered Oct 22 '22 01:10

David S