Django: Querying read-only view with no primary key

前端 未结 4 1107
广开言路
广开言路 2020-12-28 14:41
class dbview(models.Model):
    # field definitions omitted for brevity
    class Meta:
        db_table = \'read_only_view\'

def main(request):
    result = dbview         


        
相关标签:
4条回答
  • 2020-12-28 14:51

    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.

    0 讨论(0)
  • 2020-12-28 15:04

    If there really is no primary key in the view, then there is no workaround.

    Django requires each model to have exactly one field primary_key=True.

    0 讨论(0)
  • 2020-12-28 15:05

    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.
    0 讨论(0)
  • 2020-12-28 15:09

    There should have been an auto-generated id field when you ran syncdb (if there is no primary key defined in your model, then Django will insert an AutoField for you).

    This error means that Django is asking your database for the id field, but none exists. Can you run django manage.py dbshell and then DESCRIBE read_only_view; and post the result? This will show all of the columns that are in the database.

    Alternatively, can you include the model definition you excluded? (and confirm that you haven't altered the model definition since you ran syncdb?)

    0 讨论(0)
提交回复
热议问题